TCP实现聊天

tech2025-02-25  12

TCP实现聊天

客户端

/** * 客户端 */ public class TestClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream outputStream = null; try { //1.获得服务器的地址 InetAddress serverIP = InetAddress.getByName("127.0.0.1"); //2.获得服务器的端口号 int port = 9999; //3.创建一个socket连接 socket = new Socket(serverIP,port); //4.发送消息 outputStream = socket.getOutputStream(); outputStream.write("你好,我是小周周~".getBytes()); }catch (Exception e){ e.printStackTrace(); }finally { if (null != outputStream){ try { outputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != socket){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } } } }

服务端

/** * 服务端 */ public class TestServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try{ //1.创建一个服务器地址 serverSocket = new ServerSocket(9999); //循环监听 while (true){ //2.等待客户端连接 socket = serverSocket.accept(); //3.读取客户端发送过来的消息 inputStream = socket.getInputStream(); byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1){ byteArrayOutputStream.write(buffer,0,len); } System.out.println(byteArrayOutputStream.toString()); } }catch(Exception e){ e.printStackTrace(); }finally { if (null != byteArrayOutputStream){ try { byteArrayOutputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != inputStream){ try { inputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != socket){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != serverSocket){ try { serverSocket.close(); }catch (IOException e){ e.printStackTrace(); } } } } }
最新回复(0)