基於Java的Socket編寫的C/S聊天程式實現
阿新 • • 發佈:2020-03-13
一個很久以前寫的能夠支援C/S模式聊天的Demo,利用Java的Socket寫的。
只能聊一句就下線,挺low的。
伺服器端程式Server
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TestTcpServer { public static void main(String[] args) { ServerSocket ss = null; BufferedReader in = null; try { ss = new ServerSocket(8888); System.out.println("伺服器啟動"); Socket socket = ss.accept(); System.out.println("連線建立"); System.out.println(socket.getInetAddress().getHostAddress()); //伺服器接收客戶端傳送的資料 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String clientContent = in.readLine(); System.out.println("接收客戶端訊息: " +clientContent); } catch (IOException e) { e.printStackTrace(); } } }
客戶端程式Clinet
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class TestTcpClient { public static void main(String[] args) { Socket socket = null; BufferedWriter out = null; //客戶端傳送資料,伺服器端接收 try { socket = new Socket("127.0.0.1",8888); System.out.println("與伺服器連線了"); Scanner sc = new Scanner(System.in); String content = sc.nextLine(); out = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream()))); out.write(content); out.flush(); sc.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
執行樣例
注意要先起S端,否則:
好啦,先起S端:
然後S端就在等待,它“說話”也沒人理它:
接著起C端:
S端也會有響應:
然後C端發訊息:
S端收到訊息,就雙雙Over了:
到此這篇關於基於Java的Socket編寫的C/S聊天程式實現的文章就介紹到這了,更多相關Java Socket C/S聊天內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!