【JAVA】TCP通信连接

服务器对任意一个客户端连接发送问候:


import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: l
 * @Description:
 * @Date: 2019-12-12 19:41
 */
public class test04Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server_socket=null;
        Socket socket=null;
        DataOutputStream out=null;
        int port=2228;//不要定义0-1023的端口
        server_socket=new ServerSocket(port);//创建绑定端口的服务器端
while (true){
    System.out.println("服务器启动!");
    //监听并接收到此套接字的连接,此方法在连接传入之前处于阻塞状态。
    socket = server_socket.accept();
    out=new DataOutputStream(socket.getOutputStream());//创建输出流
    out.writeUTF("Welcome!");
}
    }
}

客户端:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Author: l
 * @Description:
 * @Date: 2019-12-12 19:52
 */
public class test04Client {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("127.0.0.1",2228);
         DataInputStream in = new DataInputStream(socket.getInputStream());
        String s= in.readUTF();
         System.out.println("从服务器发来的信息:"+s);

         socket.close();
         in.close();


    }
}

运行结果:

client启动了4次:

客户端:

发布了68 篇原创文章 · 获赞 20 · 访问量 6868

猜你喜欢

转载自blog.csdn.net/qq_43633973/article/details/103585841