Java 基于 TCP/IP 实现 Socket中的多客户端通信
生活随笔
收集整理的這篇文章主要介紹了
Java 基于 TCP/IP 实现 Socket中的多客户端通信
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用多線程實(shí)現(xiàn)多客戶(hù)端的通信功能, Client.java(客戶(hù)端)同上一節(jié)中的一致,不需要修改
Server.java
package com.learn;import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket;/*** 基于TCP協(xié)議的Socket通信,實(shí)現(xiàn)用戶(hù)登錄* * 服務(wù)端*/public class Server {public static void main(String[] args) {Socket socket = null;// 記錄客戶(hù)端數(shù)量int count = 0;try {// 1.創(chuàng)建一個(gè)服務(wù)器端的 Socket,即 ServerSocket,指定綁定的端,并監(jiān)聽(tīng)ServerSocket server = new ServerSocket(8888);// 2.調(diào)用 accept 方法開(kāi)始監(jiān)聽(tīng),等待客戶(hù)端連接System.out.println("****服務(wù)器開(kāi)始啟動(dòng),等待客戶(hù)端上線****");// 循環(huán)監(jiān)聽(tīng)客戶(hù)端的連接while (true) {socket = server.accept();// 創(chuàng)建一個(gè)新的線程ServerThread st = new ServerThread(socket);// 啟動(dòng)線程st.start();count++;// 客戶(hù)端數(shù)量增加System.out.println("客戶(hù)端數(shù)量為:" + count);InetAddress address = server.getInetAddress();System.out.println("客戶(hù)端IP:" + address.getHostAddress());}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }ServerThread .java
package com.learn;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket;/** 服務(wù)器端線程處理類(lèi)*/ public class ServerThread extends Thread {// 和本線程相關(guān)的 socketSocket socket = null;public ServerThread(Socket socket) {this.socket = socket;}// 線程執(zhí)行的操作,響應(yīng)客戶(hù)端的請(qǐng)求public void run() {InputStream is = null;InputStreamReader isr = null;BufferedReader br = null;OutputStream os = null;PrintWriter pw = null;try {// 3.獲取一個(gè)輸入流,用來(lái)讀取客戶(hù)端所發(fā)送的登錄信息is = socket.getInputStream();// 字節(jié)輸入流isr = new InputStreamReader(is);// 將字節(jié)流轉(zhuǎn)為br = new BufferedReader(isr);// 為輸入流添加緩沖String info = null;while ((info = br.readLine()) != null) {System.out.println("我是服務(wù)器,客戶(hù)端說(shuō)" + info);}socket.shutdownInput();// 關(guān)閉輸入流// 4.獲取輸出流os = socket.getOutputStream();pw = new PrintWriter(os);// 包裝打印流pw.write("好的,我收到消息了,你可以出去玩了");pw.flush();socket.shutdownOutput();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {// 5.關(guān)閉資源if (pw != null)pw.close();if (br != null)br.close();if (isr != null)isr.close();if (is != null)is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}客戶(hù)端,同上一節(jié)中的 Client.java 無(wú)需修改,同樣需要先運(yùn)行服務(wù)端,然后再運(yùn)行客戶(hù)端
總結(jié)
以上是生活随笔為你收集整理的Java 基于 TCP/IP 实现 Socket中的多客户端通信的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Windows 下的 PHP 编译
- 下一篇: Java 实现基于 UDP 的简单 so