Java实现TCP通信

1.服务端:

public class UdpServer {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(8899);
        Socket socket = serverSocket.accept();

        SendMsg sendMsg =new SendMsg(socket);
        ReceiveMsg receiveMsg =new ReceiveMsg(socket,"客户端");

        new Thread(sendMsg).start();
        new Thread(receiveMsg).start();

    }
}

2.用户端: ​

public class TcpUser {
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket(InetAddress.getLocalHost(),8899);

        SendMsg sendMsg =new SendMsg(socket);
        ReceiveMsg receiveMsg =new ReceiveMsg(socket,"服务端");
        new Thread(sendMsg).start();
        new Thread(receiveMsg).start();

    }
}

3.接受信息的线程:

public class ReceiveMsg implements Runnable {
    private Socket socket;
    private String fromName;
    public ReceiveMsg(Socket socket,String fromName) {
        this.socket = socket;
        this.fromName =fromName;
    }
    @Override
    public void run() {
        while(true){
            try {
                InputStream is = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len = is.read(bytes);
                System.out.println(fromName+": "+new String(bytes,0,len));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.发送信息的线程:

public class SendMsg implements Runnable{
    private Socket socket;
    public SendMsg(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run(){
        Scanner scanner = new Scanner(System.in);
        try {
            while(true){
                OutputStream os = socket.getOutputStream();
                String msg =scanner.nextLine();
                if(msg.equals("exit")){
                    System.out.println("连接已断开!");
                    os.write("已断开连接!".getBytes());
                    break;
                }
                os.write(msg.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结:TCP程序需先确定 谁是服务器 谁是用户端。服务器通过serversocket生成一个Socket对象,再将socket传递到两个线程。退出时需将流和socket关闭。

     

你可能感兴趣的:(Java学习,java)