6.TCP实现聊天
打电话:需要连接,接通了后才可以
客户端:
- 通过Socket连接服务器
- 发送消息
1 package com.Inet.lesson2; 2 3 import java.io.IOException; 4 import java.io.OutputStream; 5 import java.net.InetAddress; 6 import java.net.Socket; 7 8 //客户端 9 public class TcpClientDemo01 { 10 public static void main(String[] args) { 11 Socket socket = null; 12 OutputStream os = null; 13 14 try { 15 //1.要知道服务器的地址 16 InetAddress serverIP = InetAddress.getByName("127.0.0.1"); 17 int port = 9999; 18 //2.创立一个socket连接 19 socket = new Socket(serverIP, port); 20 //3.发送消息 IO流 21 os = socket.getOutputStream(); 22 os.write("你好,世界".getBytes()); 23 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } finally { 27 //关闭资源,先开后关 28 if (os != null) { 29 try { 30 os.close(); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 } 35 if (socket != null) { 36 try { 37 socket.close(); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 } 41 } 42 43 } 44 } 45 }
服务器:
- 建立服务的端口 ServerSocket
- 等待用户的链接 accept
- 接收用户的消息
1 package com.Inet.lesson2; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 //服务端 10 public class TcpServerDemo01 { 11 public static void main(String[] args) { 12 ServerSocket serverSocket = null; 13 Socket socket = null; 14 InputStream is = null; 15 ByteArrayOutputStream baos = null; 16 try { 17 //1.我得有一个地址 18 serverSocket = new ServerSocket(9999); 19 while (true) { 20 //2.等待客户端连接过来 21 socket = serverSocket.accept(); 22 //3.读取客户端的消息 23 is = socket.getInputStream(); 24 //管道流 25 baos = new ByteArrayOutputStream(); 26 byte[] buffer = new byte[1024]; 27 int len; 28 while ((len = is.read(buffer)) != -1) { 29 baos.write(buffer, 0, len); 30 } 31 System.out.println(baos.toString()); 32 } 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } finally { 36 //关闭资源 37 if (baos != null) { 38 try { 39 baos.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 if (is != null) { 45 try { 46 is.close(); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 } 51 if (socket != null) { 52 try { 53 socket.close(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 if (serverSocket != null) { 59 try { 60 serverSocket.close(); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 } 64 } 65 } 66 } 67 }
测试:
先启动服务端,再启动客户端,服务器端使用while(true)不停的监听,所以启动一次客户端,服务器端就会收到。