Socket 簡單通訊程式碼
阿新 • • 發佈:2019-02-12
SocketService.java 伺服器
SocketTest.java 客戶端
客戶端和伺服器可以相互通訊
package com.travelsky.quartz.bean; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; public class SocketService { private static ServerSocket server; public static void main(String[] args) { try { server=new ServerSocket(4331); System.out.println("等待客戶端呼叫"); Socket sok = server.accept(); DataOutputStream out = new DataOutputStream(sok.getOutputStream()); DataInputStream in = new DataInputStream(sok.getInputStream()); String s = null; int i = 0; while(true){ // s = in.readUTF(); out.writeUTF(++i+"伺服器傳送的訊息"); // System.out.println("伺服器收到:"+s); Thread.sleep(2000); } } catch (Exception e) { e.printStackTrace(); } } }
SocketTest.java 客戶端
package com.travelsky.quartz.bean; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SocketTest { private static Socket socket; public static void main(String[] arg){ try { socket = new Socket("172.29.1.178",4331);//本機ip,埠隨意,只要是未被佔用的 DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); String s = null; int i =0; while(true){ // out.writeUTF("使用者自定義訊息"); s = in.readUTF(); System.out.println(++i+"客戶端收到:"+s); Thread.sleep(500); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ closeSocket(); } } private static void closeSocket(){ if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
客戶端和伺服器可以相互通訊