赞
踩
客户端:
1. 连接服务器Socket
2.发送消息
服务器:
1. 建立服务器的端口ServerSocket
2. 等待客户端的连接accept
3. 接受客户端的消息
package com.tx.socket.tcp; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; /** * @Auther lmy * @Date 2021/5/14 2:28 * @Description 客户端 */ public class TcpClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { //1.要知道服务器的地址,端口号 InetAddress serverIP = InetAddress.getByName("127.0.0.1"); int port = 9999; //2.创建一个socket连接 socket = new Socket(serverIP, port); System.out.println("客户端启动了..."); //3.发送消息 io流 os = socket.getOutputStream(); os.write("你好,服务器".getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.tx.socket.tcp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; /** * @Auther lmy * @Date 2021/5/14 2:28 * @Description 服务端 */ public class TcpServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream in = null; ByteArrayOutputStream baos = null; try { //1.服务器得有一个地址 serverSocket = new ServerSocket(9999); System.out.println("服务器启动了..."); //2.等待客户端连接过来 while (true) { socket = serverSocket.accept(); //读取客户端的消息 in = socket.getInputStream(); //管道流 baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = in.read(bytes)) != -1) { baos.write(bytes, 0, len); } System.out.println(baos.toString()); } /* //会出现中文乱码 byte[] bytes = new byte[1024]; int len; while ((len = in.read(bytes)) != -1) { String msg = new String(bytes, 0, len); System.out.println(msg); } */ } catch (Exception e) { e.printStackTrace(); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
1.先启动服务器进行监听
2.启动客户端,给服务器发送消息
3.服务器接受到消息
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。