标签:客户 cep 代码 lin server tput edr [] add
socket通信有几个步骤
服务端:
1.创建服务端,监听端口
2.服务端死循环接受客户端请求
3.获取客户端请求并输出
客户端:
1.创建socket连接服务端
2.向服务端发送数据
服务端代码如下:
public class Server { public static void main(String[] args) throws IOException { createServer(); } private static void createServer() throws IOException { //1.创建服务端socket,监听端口 ServerSocket server = new ServerSocket(8888); //2.死循环等待客户端连接 Socket client = null; while(true){ //3.获取客户端连接来的socket client = server.accept(); if(client !=null){ System.out.println("客户端连接来了"); //4.获取客户端输入并读取出来 BufferedReader read = new BufferedReader(new InputStreamReader(client.getInputStream())); System.out.println(read.readLine()); read.close(); } } } }
客户端代码如下
public class Client { public static void main(String[] args) throws IOException { createClient(); } private static void createClient() throws UnknownHostException, IOException { //创建客户端 Socket client = new Socket("127.0.0.1", 8888); //客户端连接服务端 // SocketAddress endpoint = new InetSocketAddress("127.0.0.1", 8888); OutputStream os = client.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); bw.write("hello"); bw.flush(); os.close(); osw.close(); } }
标签:客户 cep 代码 lin server tput edr [] add
原文地址:https://www.cnblogs.com/jiaqirumeng/p/9058342.html