版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
第Java實現(xiàn)局域網(wǎng)聊天小程序本文實例為大家分享了Java實現(xiàn)局域網(wǎng)聊天的具體代碼,供大家參考,具體內(nèi)容如下
開發(fā)環(huán)境:
IDEA2025.2集成開發(fā)工具。
實現(xiàn)功能:
1、用戶上線,向服務器通知并注冊。
2、同局域網(wǎng)下,所有注冊用戶可以進行群聊。
3、同局域網(wǎng)下,所有用戶可與任意已注冊用戶進行私聊。
4、用戶下線,通知服務器,服務器更新信息。
實現(xiàn)原理:
1、服務器端實例化一個ServerSocket對象,調(diào)用accept方法等待客戶端連接到服務器。
2、客戶端實例化Socket對象,并使用構造方法與服務器建立鏈接。
3、服務器端根據(jù)客戶端輸入信息,辨別客戶端請求的功能從而做出相應響應。
實用技術:
為了能夠高效的處理客戶端的請求,在服務器端使用多線程處理客戶端請求。并且使用ConcurrentHashMap來存儲所有注冊過的客戶端。
項目源碼(解釋寫在代碼的注釋當中):
服務器端:
importjava.io.IOException;
importjava.io.PrintStream;
import.ServerSocket;
import.Socket;
importjava.util.Map;
importjava.util.Scanner;
importjava.util.Set;
importjava.util.concurrent.*;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
publicclassManyThreadServer{
//存儲所有注冊的客戶端
privatestaticMapString,SocketclientMap=newConcurrentHashMapString,Socket
//具體的處理每個客戶端的請求
privatestaticclassExcuteClientimplementsRunnable{
privateSocketclient;
publicExcuteClient(Socketclient){
this.client=client;
}
@Override
publicvoidrun(){
try{
//獲取客戶端的輸出流,讀取客戶端消息,并處理
Scannerin=newScanner(client.getInputStream());
StringstrFromClient;
while(true){
if(in.hasNextLine()){
strFromClient=in.nextLine();
//在Windows下默認換行是:\r\n,所以把\r要轉換為空字符串
Patternpattern=Ppile("\r");
Matchermatcher=pattern.matcher(strFromClient);
strFromClient=matcher.replaceAll("");
//注冊流程
if(strFromClient.startsWith("useName")){
StringuseName=strFromClient.split("\\:")[1];
registerUser(useName,client);
continue;
}
//群聊功能
if(strFromClient.startsWith("G")){
Stringmsg=strFromClient.split("\\:")[1];
groupChat(msg,client);
continue;
}
//私聊功能
if(strFromClient.startsWith("P")){
StringuserName=strFromClient.split("\\:")[1].split("-")[0];
Stringmsg=strFromClient.split("\\:")[1].split("-")[1];
privateChat(userName,msg,client);
continue;
}
//用戶退出
if(strFromClient.startsWith("B")){
StringuserName=null;
//根據(jù)Socket找到UserName
for(StringkeyName:clientMap.keySet()){
if(clientMap.get(keyName).equals(client)){
userName=keyName;
}
}
System.out.println("用戶"+userName+"下線了。。。");
clientMap.remove(userName);
System.out.println("當前共有用戶"+clientMap.size()+"人");
continue;
}
else{
PrintStreamout=newPrintStream(client.getOutputStream(),true,"UTF-8");
out.println("輸入錯誤。。。");
}
}
}
}catch(IOExceptione){
e.printStackTrace();
}
}
privatevoidregisterUser(Stringname,Socketclient){
System.out.println("用戶:"+name+"已上線!");
clientMap.put(name,client);
System.out.println("當前在線人數(shù):"+clientMap.size()+"人!");
//既然是用戶在注冊,所以這里服務器通知用戶注冊結果
try{
PrintStreamout=newPrintStream(client.getOutputStream(),true,"UTF-8");
out.println("用戶注冊成功!");
}catch(IOExceptione){
e.printStackTrace();
}
}
privatevoidgroupChat(Stringmsg,Socketclient){
//取出clientMap中所有的Entry對象,遍歷每個用戶,并且發(fā)送消息
SetMap.EntryString,SocketclientSet=clientMap.entrySet();
for(Map.EntryString,Socketentry:clientSet){
try{
Socketsocket=entry.getValue();
//取得輸出流,向客戶端發(fā)送消息
PrintStreamout=newPrintStream(socket.getOutputStream(),true,"UTF-8");
out.println("由端口號為"+client.getPort()+"發(fā)來的群聊消息:"+msg);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
privatevoidprivateChat(StringuserName,Stringmsg,Socketclient){
SocketprivateSocket=clientMap.get(userName);
try{
PrintStreamout=newPrintStream(privateSocket.getOutputStream(),true,"UTF-8");
out.println("由端口號為:"+client.getPort()+"發(fā)來的消息:"+msg);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[]args)throwsException{
//為了提高效率,這里使用多線程進行處理
ExecutorServiceexecutorService=Executors.newFixedThreadPool(30);
//實例化ServerSocket對象,并指定IP為本地主機,端口號為6666
ServerSocketserverSocket=newServerSocket(6666);
for(inti=0;ii++){
System.out.println("等待用戶連接。。。");
//等待客戶端連接服務器
Socketclient=serverSocket.accept();
System.out.println("有客戶端連接,端口號為:"+client.getPort());
//啟動線程,并處理客戶端請求
executorService.submit(newExcuteClient(client));
}
//關閉線程,關閉服務器
executorService.shutdown();
serverSocket.close();
}
}
客戶端:
importjava.io.IOException;
importjava.io.PrintStream;
import.Socket;
importjava.util.Scanner;
*
接收服務端發(fā)來的消息
classFromServerimplementsRunnable{
Socketclient;
publicFromServer(Socketclient){
this.client=client;
}
@Override
publicvoidrun(){
try{
Scannerin=newScanner(client.getInputStream());
while(true){
if(in.hasNextLine()){
System.out.println("服務器:"+in.nextLine());
}
//判斷客戶端是否退出,如果推出,跳出循環(huán),并關閉流
if(client.isClosed()){
System.out.println("客戶端關閉。。。");
break;
}
}
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
*
向服務端發(fā)出消息
classToServer
implementsRunnable{
Socketclient;
publicToServer(Socketclient){
this.client=client;
}
@Override
publicvoidrun(){
try{
Scannerscanner=newScanner(System.in);
PrintStreamout=newPrintStream(client.getOutputStream(),true,"UTF-8");
while(true){
System.out.println("請輸入信息:");
StringstrToserver;
if(scanner.hasNextLine()){
strToserver=scanner.nextLine().trim();
out.println(strToserver);
//客戶端退出標志:B
if(strToserver.startsWith("B")){
System.ou
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 交管站財務制度
- 村衛(wèi)生室醫(yī)師定考制度
- 工程檢測公司財務制度
- 旅游景區(qū)衛(wèi)生獎罰制度
- 六安公共衛(wèi)生體系制度
- 財務制度管理kpi
- 警校宿舍衛(wèi)生扣分制度
- 電商公司運營獎懲制度
- 運營崗提成制度方案模板
- 采石場財務制度規(guī)定
- T-CCTAS 237-2025 城市軌道交通市域快線車輛運營技術規(guī)范
- 園林環(huán)衛(wèi)安全培訓內(nèi)容課件
- 軟件系統(tǒng)上線測試與驗收報告
- 冬季交通安全測試題及答案解析
- 2025年國家能源局系統(tǒng)公務員面試模擬題及備考指南
- (2025年標準)圈內(nèi)認主協(xié)議書
- 2025年安徽省中考化學真題及答案
- 2025年軍隊文職人員統(tǒng)一招聘面試( 臨床醫(yī)學)題庫附答案
- 海馬體核磁掃描課件
- 某電力股份企業(yè)同熱三期2×100萬千瓦項目環(huán)評報告書
- 2026屆上海市部分區(qū)中考一模語文試題含解析
評論
0/150
提交評論