16 Socket通信(简单例子)
服务端代码:
1 import java.io.*; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 import java.util.Date; 5 6 /** 7 * socket服务端简单实现,主要作用测试客户端是否可以成功发送数据 8 */ 9 public class SocketServer { 10 11 public static void main(String[] args) { 12 try { 13 ServerSocket serverSocket = new ServerSocket(9999); 14 Socket socket=null; 15 while(true) { 16 socket = serverSocket.accept(); 17 while(socket.isConnected()) 18 { 19 // 读取客户端数据 20 InputStream info = socket.getInputStream(); 21 DataInputStream dis = new DataInputStream(info); 22 String data=""; 23 while((data=dis.readUTF()).length()>0) { 24 //存在数据则输出 25 System.out.println(data); 26 // 向客户端输出数据 说明数据接收成功 27 OutputStream os = socket.getOutputStream(); 28 DataOutputStream dos = new DataOutputStream(os); 29 dos.writeUTF("ok!"+new Date()); 30 dos.flush(); 31 } 32 //400ms输出一次数据 33 try { 34 Thread.sleep(400L); 35 } catch (InterruptedException e) { 36 e.printStackTrace(); 37 } 38 } 39 //100ms检测一次连接 40 try { 41 Thread.sleep(100L); 42 } catch (InterruptedException e) { 43 e.printStackTrace(); 44 } 45 } 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } 49 } 50 }
客户端代码:
1 import java.io.*; 2 import java.net.InetAddress; 3 import java.net.Socket; 4 import java.net.SocketAddress; 5 import java.net.UnknownHostException; 6 7 /** 8 * socket客户端简单实现,主要作用是往本地固定端口发送数据 9 */ 10 public class SocketClient { 11 public static void main(String[] args) { 12 try { 13 //建立一个本机socket客户端 14 Socket socket = new Socket("127.0.0.1", 9999); 15 // 向服务器端发送数据 16 OutputStream os = socket.getOutputStream(); 17 DataOutputStream bos = new DataOutputStream(os); 18 //每隔20ms发送一次数据 19 while(true){ 20 bos.writeUTF("Connect 123 test spark streaming abc xyz hik"); 21 bos.flush(); 22 //200ms发送一次数据 23 try { 24 Thread.sleep(200L); 25 } catch (InterruptedException e) { 26 e.printStackTrace(); 27 } 28 // 接收服务器端数据 29 InputStream is = socket.getInputStream(); 30 DataInputStream dis = new DataInputStream(is); 31 System.out.println(dis.readUTF()); 32 } 33 34 } catch (UnknownHostException e) { 35 e.printStackTrace(); 36 } catch (IOException e) { 37 e.printStackTrace(); 38 } 39 } 40 }
本文来自博客园,作者:life_start,转载请注明原文链接:https://www.cnblogs.com/yangh2016/p/5742238.html