socket客户端与服务端的简单Demo
与外系统开发接口,发现系统采用的是Socket来做通信的,整理个简单的Demo,复习下基础。
客户端Demo
1 package com.socket; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.Socket; 7 8 public class SocketClientDemo { 9 public static void main(String[] args) { 10 Socket sc = null; 11 InputStream ips = null; 12 OutputStream ops = null; 13 try { 14 // 设置发送服务端的ip和端口 15 sc = new Socket("127.0.0.1", 8081); 16 // 设置超时时间 17 sc.setSoTimeout(10000); 18 // 发送服务端 19 ops = sc.getOutputStream(); 20 ops.write("Socket客户端发送请求报文内容".getBytes("UTF-8")); 21 ops.flush(); 22 System.out.println("客户端报文发送完毕"); 23 24 // 接受服务端响应的内容 25 ips = sc.getInputStream(); 26 byte[] rsp = new byte[256]; 27 // 将服务端返回的字节流读入字节数组 28 ips.read(rsp); 29 // 将字节流数组安装UTF-8的格式转换为String类型 30 String rspStr = new String(rsp, "UTF-8"); 31 System.out.println("服务端返回的响应为:" + rspStr); 32 33 } catch (Exception e) { 34 e.getStackTrace(); 35 }finally { 36 37 // 关闭流 38 if(ips != null) { 39 try { 40 ips.close(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 if(ops != null) { 46 try { 47 ops.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 // 关闭Socket 53 if(sc != null) { 54 try { 55 sc.close(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } 59 } 60 } 61 62 } 63 }
服务端Demo
1 package com.socket; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class SocketServerDemo { 10 public static void main(String[] args) { 11 ServerSocket ss = null; 12 InputStream ips = null; 13 OutputStream ops = null; 14 try { 15 // 服务端监听8081端口 16 ss = new ServerSocket(8081); 17 System.out.println("服务端已启动"); 18 // 阻塞等待客户端请求 19 Socket accept = ss.accept(); 20 // 获取客户端的输入流 21 ips = accept.getInputStream(); 22 byte[] reqByte = new byte[256]; 23 // 将输入流的内容读入字节数组 24 ips.read(reqByte); 25 String reqStr = new String(reqByte, "UTF-8"); 26 System.out.println("服务端接收到客户端请求报文:" + reqStr); 27 28 // 服务端返回信息给客户端 29 ops = accept.getOutputStream(); 30 ops.write("服务端已收到客户端的请求".getBytes("UTF-8")); 31 ops.flush(); 32 System.out.println("服务端响应完毕"); 33 34 } catch (Exception e) { 35 e.getStackTrace(); 36 }finally { 37 // 关闭流 38 if(ips != null) { 39 try { 40 ips.close(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 if(ops != null) { 46 try { 47 ops.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 // 关闭Socket 53 if(ss != null) { 54 try { 55 ss.close(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } 59 } 60 } 61 } 62 }

浙公网安备 33010602011771号