简单Client与Server的单向通信和双向通信
程序员文章站
2022-07-12 17:30:26
...
从Console中读取内容:
BufferedReader inputReader; // Alt + Shift + z try...catch等快捷键 // 从Console读取内容 try { inputReader = new BufferedReader(new InputStreamReader(System.in)); String inputContent; while (!(inputContent = inputReader.readLine()).equals("bye")) { System.out.println(inputContent); } } catch (Exception e) { e.printStackTrace(); }
一.单向通信
Client -> Server
SocketClient.java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class SocketClient { public static void main(String[] args) { SocketClient client = new SocketClient(); client.start(); } public void start() { BufferedReader inputReader = null; BufferedWriter writer = null; Socket socket = null; // 从Console读取内容 try { socket = new Socket("127.0.0.1", 9898); // 从socket进行写入 writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); inputReader = new BufferedReader(new InputStreamReader(System.in)); String inputContent; while (!(inputContent = inputReader.readLine()).equals("bye")) { writer.write(inputContent + "\n"); writer.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); inputReader.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
SocketServer.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class SocketServer { public static void main(String[] args) { SocketServer socketServer = new SocketServer(); socketServer.startServer(); } public void startServer() { ServerSocket serverSocket = null; BufferedReader reader = null; Socket socket = null; try { // 端口号只要不冲突就行 serverSocket = new ServerSocket(9898); System.out.println("server started.."); // 进入阻塞状态,等待客户端接入 socket = serverSocket.accept(); System.out.println("client " + socket.hashCode() + " connected"); // 从socket中读取数据 reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String receiveMsg; while ((receiveMsg = reader.readLine()) != null) { // 以"\n"结束 System.out.println(receiveMsg); } } catch (Exception e) { e.printStackTrace(); } finally { try { reader.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
二.Client Server双向通信
即时接受消息,也就是所谓的长连接,记得要先启动Server。
SocketClient2.java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class SocketClient2 { public static void main(String[] args) { SocketClient2 client = new SocketClient2(); client.start(); } public void start() { BufferedReader inputReader = null; // 从socket读取 BufferedReader reader = null; BufferedWriter writer = null; Socket socket = null; // Alt + Shift + z try...catch等快捷键 // 从Console读取内容 try { socket = new Socket("127.0.0.1", 9898); // 用于读取服务器返回的数据 reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 从socket进行写入 writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); inputReader = new BufferedReader(new InputStreamReader(System.in)); String inputContent; while (!(inputContent = inputReader.readLine()).equals("bye")) { writer.write(inputContent + "\n"); writer.flush(); // System.out.println(inputContent); // 服务器返回的数据 String response = reader.readLine(); System.out.println(response); } } catch (Exception e) { e.printStackTrace(); } finally { try { reader.close(); writer.close(); inputReader.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
SocketServer2.java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class SocketServer2 { public static void main(String[] args) { SocketServer2 socketServer = new SocketServer2(); socketServer.startServer(); } public void startServer() { ServerSocket serverSocket = null; BufferedReader reader = null; BufferedWriter writer = null; Socket socket = null; try { // 端口号只要不冲突就行 serverSocket = new ServerSocket(9898); System.out.println("server started.."); // 进入阻塞状态,等待客户端接入 socket = serverSocket.accept(); System.out.println("client " + socket.hashCode() + " connected"); // 从socket中读取数据 reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String receiveMsg; while ((receiveMsg = reader.readLine()) != null) { // 以"\n"结束 System.out.println(receiveMsg); writer.write("server reply:" + receiveMsg + "\n"); writer.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { reader.close(); writer.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
三.Socket模拟http请求响应(仅模拟)
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.Random; public class SimpleServer { private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; private Random random = new Random(); public SimpleServer() { try { this.ss = new ServerSocket(9898); System.out.println("The server is waiting your input..."); for (;;) { this.socket = this.ss.accept(); this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); this.out = new PrintWriter(this.socket.getOutputStream(), true); String line = this.in.readLine(); System.out.println("you input is : " + line); String echo = randomEcho(); System.out.println("echo : " + echo); StringBuilder sb = new StringBuilder(); sb.append("HTTP/1.1 200 OK").append("\n") .append("Content-Type:application/x-www-form-urlencoded;charset=UTF-8").append("\n") .append("Date:").append(new Date().toString()).append("\n").append("Content-Length:") .append(echo.getBytes().length).append("\n").append("\n").append(echo); this.out.println(sb.toString()); this.out.flush(); this.out.close(); this.in.close(); this.socket.close(); if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit") || line.equalsIgnoreCase("bye")) { break; } } this.ss.close(); } catch (Exception e) { e.printStackTrace(); } } private String randomEcho() throws Exception { int num = this.random.nextInt(); StringBuilder sb = new StringBuilder(); sb.append("respCode=").append("0000").append("&").append("respMsg=").append("随机消息:" + num); // String signature = SignUtil.sign(ResourcesUtils.getInstance().tppPriKey().trim().getBytes("UTF-8"), sb.toString()); // sb.append("&").append("signature=").append(signature); return sb.toString(); } public static void main(String[] args) { new SimpleServer(); } }
参考文章:http://blog.csdn.net/DuanLiuchang/article/details/70148894?locationNum=13&fps=1
上一篇: 数据结构与算法——二叉树遍历
下一篇: 数据结构与算法-表