基于Java的Socket編寫的C/S聊天程序實現
一個很久以前寫的能夠支持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聊天內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: