Java实现TCP通信服务端、用户端、接收线程 本文共有2327个字,关键词: 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关闭。 × yihong (๑>ڡ<)☆谢谢老板~ 2元 5元 10元 50元 100元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 码农心得 2022-09-07 评论 1054 次浏览