BIO-同步阻塞IO,直接上代码。
服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;
public class SocketServer {
public static void main(String[] args) {
try { ServerSocket socket = new ServerSocket(8082); while (true) { System.out.println("等待客户端连接..."); Socket client = socket.accept(); OutputStream output = client.getOutputStream(); output.write(("客户端[" + client.getPort() + "]你好,你已成功连接到8082服务端").getBytes());
output.flush(); System.out.println("客户端已连接:" + client.getPort()); try { InputStream input = client.getInputStream(); byte[] bytes = new byte[1024]; while (input.read(bytes) != -1) { output.write(("收到了你的消息:" + new String(bytes)).getBytes()); output.flush(); System.out.println("收到客户端消息:" + new String(bytes).trim()); } } catch (IOException ex) { System.err.println("引发异常:" + ex.getMessage()); } } } catch (IOException e) { e.printStackTrace(); } } }
|
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner;
public class SocketClient {
public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in); Socket socketClient = new Socket("127.0.0.1", 8082);
new Thread(() -> { try { InputStream input = socketClient.getInputStream(); byte[] bytes = new byte[1024 * 4]; while ((input.read(bytes)) != -1) { System.out.println("收到服务端消息:" + new String(bytes).trim()); } } catch (IOException e) { e.printStackTrace(); } }).start(); OutputStream output = socketClient.getOutputStream(); while (true) { String str = scanner.nextLine(); if ("exit".equals(str)) { output.close(); socketClient.close(); break; } else { output.write(str.getBytes()); output.flush(); } } } catch (IOException e) { e.printStackTrace(); } } }
|
很简单的一个小栗子,看一看然后自己瞧一瞧,也会更容易理解。代码可以直接运行的。
IDEA小TIPS:
复制完整的代码文本,在IDEA里可以直接粘贴会根据文本直接生成一个类。