以下實例示範如何實現客戶端發送訊息到伺服器,伺服器接收到訊息並讀取輸出,然後寫出到客戶端客戶端接收到輸出。
1、建立伺服器端
伺服器建立通訊ServerSocket
伺服器建立Socket接收客戶端連線
。端發送資料訊息
伺服器端程式碼:
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.ServerSocket; import java.net.Socket;public class Server { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8888); System.out.println("启动服务器...."); Socket s = ss.accept(); System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器"); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //读取客户端发送来的消息 String mess = br.readLine(); System.out.println("客户端:"+mess); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write(mess+"\n"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } }}
启动服务器....
2、建立客戶端
IO輸出流向伺服器傳送資料訊息
建立IO輸入流讀取伺服器發送來的資料訊息
客戶端程式碼:
/* author by w3cschool.cc Main.java */import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStream; import java.io.InputStreamReader;import java.io.OutputStream; import java.io.OutputStreamWriter;import java.net.Socket; import java.net.UnknownHostException;public class Client { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1",8888); //构建IO InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); //向服务器端发送一条消息 bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n"); bw.flush(); //读取服务器返回的消息 BufferedReader br = new BufferedReader(new InputStreamReader(is)); String mess = br.readLine(); System.out.println("服务器:"+mess); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
服务器:测试客户端和服务器通信,服务器接收到消息返回到客户端
rrreee
以上程式碼運作輸出結果為: