Socket网络编程(三)
TCP协议网络通讯案例(http协议)
1、创建TcpServer(tcp服务端)
package com.cppdy.tcp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; //tcp服务端 public class TcpServer { public static void main(String[] args) throws Exception { System.out.println("tcp服务端启动啦……"); ServerSocket serverSocket = new ServerSocket(8080); try { // 会阻塞在这里,等待连接 Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); byte[] bytes = new byte[1024]; int length = inputStream.read(bytes); String result = new String(bytes, 0, length); System.out.println("服务端接收到客户端发送的消息:" + result); OutputStream outputStream = accept.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.println("服务器收到消息了,这是服务器自动反馈……"); printWriter.flush(); accept.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); } finally { serverSocket.close(); } } }
2、创建TcpClient(tcp客户端)
package com.cppdy.tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; //tcp客户端 public class TcpClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("127.0.0.1", 8080); try { OutputStream outputStream = socket.getOutputStream(); String msg = "吹泡泡的魚"; outputStream.write(msg.getBytes()); System.out.println("客户端发送消息完毕……"); InputStream inputStream = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String result = br.readLine(); System.out.println("客户端==》服务器返回的结果:" + result); } catch (IOException e) { e.printStackTrace(); } finally { socket.close(); } } }