您好,登錄后才能下訂單哦!
話不多說,直接上代碼和運行結果。
服務端代碼:
public static void main(String[] args) {
final int PORT = 8899;
ServerSocket serverSocket = null;
BufferedWriter writer = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("服務器已啟動!正在監(jiān)聽端口"+PORT);
while (true){
Socket socket = serverSocket.accept();
System.out.println("客戶端 "+socket.getPort()+" 已連接");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String message = reader.readLine();
if (message != null){
System.out.println("收到一條來自客戶端 "+socket.getPort()+" 發(fā)送的消息:"+message);
}
//加了\n readLine才能生效
writer.write("你才是" + message + "\n");
writer.flush(); //清理緩沖區(qū)
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null){
try {
writer.close();
System.out.println("服務器掛掉了。。再見");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客戶端代碼:
public static void main(String[] args) {
final String Host = "127.0.0.1";
final int Port = 8899;
BufferedWriter writer = null;
try {
Socket socket = new Socket(Host,Port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String message = console.readLine();
writer.write(message+"\n");
writer.flush();
String responseMsg = reader.readLine();
System.out.println("收到了來自服務器的回復:" + responseMsg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null){
try {
writer.close();
System.out.println("客戶端關閉了連接");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
先運行Server代碼,此時服務成功啟動!:
再運行客戶端代碼,此時服務端和客戶端連接成功!:
在客戶端發(fā)送消息:
這個教程是一個多線程的版本,其實就是把服務端的代碼中可以復用的部分抽出來單獨作為一個內部類,繼承Thread,然后在while循環(huán)里,每當有一個客戶端前來訪問,都將開啟一個線程專門來處理這個客戶端的請求
實際上,上面的極簡版本代碼,完全也可以多復制幾個Client, 然后同時運行,Server端代碼會一個個的按照順序收到客戶端的請求并返回對應的結果,while循環(huán)永不疲倦,除非斷電。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。