![Socket和多線程編程的聊天程序實現_第1頁](http://file4.renrendoc.com/view/cde75d77c14a1557bab1f9bfcd3fbdc7/cde75d77c14a1557bab1f9bfcd3fbdc71.gif)
![Socket和多線程編程的聊天程序實現_第2頁](http://file4.renrendoc.com/view/cde75d77c14a1557bab1f9bfcd3fbdc7/cde75d77c14a1557bab1f9bfcd3fbdc72.gif)
![Socket和多線程編程的聊天程序實現_第3頁](http://file4.renrendoc.com/view/cde75d77c14a1557bab1f9bfcd3fbdc7/cde75d77c14a1557bab1f9bfcd3fbdc73.gif)
![Socket和多線程編程的聊天程序實現_第4頁](http://file4.renrendoc.com/view/cde75d77c14a1557bab1f9bfcd3fbdc7/cde75d77c14a1557bab1f9bfcd3fbdc74.gif)
![Socket和多線程編程的聊天程序實現_第5頁](http://file4.renrendoc.com/view/cde75d77c14a1557bab1f9bfcd3fbdc7/cde75d77c14a1557bab1f9bfcd3fbdc75.gif)
版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
濱江學院課程設計任務書學年學期2012-2013學年第二學期
課程名稱用socket實現聊天程序 院系計算機系 專業(yè)計科 姓名周洲指導教師 朱節(jié)中二O一三年七月七日用Socket的編程機制實現聊天程序10計科周洲20092308065摘要:Socket是基于TCP/IP的網絡上運行的兩個程序間雙向通訊的一種連接機制,包中包含Socket類,用以快速地開發(fā)網絡通信程序。通過實例模型探討基于Java的Socket通信程序的一般結構。對開發(fā)一般性的通信軟件,有一定的參考價值。關鍵詞:Java;網絡;SocketSocketProgrammingBasedonTCP/IPinJavaAbstract:Socketisoneofthetwo-waycommunication'sendbetweentwoproceduresthatareoperatedonthenetworkbasedonTCP/IP.JbagincludesSockets,whichisusedtodevelopthenetworkcommunicationprocedurefast.ThispaperprobesintothegeneralstructurebasedonSocketcommunicationprocedureofJavathroughtheinstancemodel.Thegeneralcommunicationsoftwarecanbedevelopedbasedonthisone,sothereiscertainreferencevalue.Keywords:ava;network;Socket;communication一、課題內容和要求1.課題內容基于Socket和多線程編程的聊天程序實現2.課題要求網絡聊天程序設計非常復雜,允許多個人同時聊天更加需要多線程技術的支持,請實現一個簡單的多線程網絡聊天程序模擬。二、設計思路分析1.在網絡越來越發(fā)達的今天,人們對網絡的依賴越來越強,網絡聊天已經成了許多人生活中必不可少的一部分,基于這樣的需求,出現了許多網絡聊天通信工具,像QQ,MSN等等,但是人們已經不再滿足于單一的兩個人之間的聊天,而是對多人同時聊天產生了興趣,于是出現了網絡聊天室,不同地方的人可以在那個虛擬的聊天室里面熱烈聊天。基于這樣的想法,我們用JAVA設計一個多人同時聊天的小程序,用Socket編程實現網絡通訊,面向連接的,采用多線程的實現技術。2.在程序中,可以設置加入連接的最大數目,通過更改IP地址和端口號,成為不同的客戶端,與服務器端連接,進行多用戶聊天。3.為方便用戶交互,我們采用圖形化的用戶界面。實現了好友添加,消息收發(fā)、顯示等基本功能。三、概要設計該網絡聊天程序大致分為三個主要部分:客戶端、服務器端和用戶圖形界面。各個部分的初步設計思想、流程及存儲結構如下:1.程序整體框架:主程序監(jiān)聽一端口,等待客戶接入;同時構造一個線程類,準備接管會話。當一個Socket會話產生后,將這個會話交給線程處理,然后主程序繼續(xù)監(jiān)聽。
Socket對象
SocketClient[]=newSocket[10];
SocketClient1=null;
inti=0;
TextAreain;
intport,k=0,l=0;
PrintStreamtheOutputStream;
Facechat;
publicServer(intport,Facechat){
try{
this.port=port;
skt=newServerSocket(port);
this.chat=chat;
}catch(IOExceptione){
chat.ta.append(e.toString());
}
}
publicvoidrun(){
chat.ta.append("等待連線......");
while(true){
try{
Client[k]=skt.accept();
//當有客戶端連接時就新建一個子線程
if(i<2){
ServerThreadserver[]=newServerThread[10];
server[k]=newServerThread(Client[k],this.chat,i);
l=server.length;
server[k].start();
chat.ta.append(“客戶端“+Client[k].getInetAddress()+"已連線\n");
//for(intj=0;j<server.length;j++)
theOutputStream=newPrintStream(server[k].getClient().getOutputStream());
i=server[k].getI();
k++;
}else{
//theOutputStream=newPrintStream(null);
}
}catch(SocketExceptione){
}catch(IOExceptione){
chat.ta.append(e.toString());
}
}
}
publicvoiddataout(Stringdata){
//for(intj=0;j<l;j++)
theOutputStream.println(data);
}}classServerThreadextendsThread{
ServerSocketskt;
SocketClient;
TextAreain;
intport,i;
BufferedReadertheInputStream;
PrintStreamtheOutputStream;
Stringreadin;
Facechat;//服務端子線程
publicServerThread(Sockets,Facechat,inti){
this.i=++i;
Client=s;
this.chat=chat;
}
publicintgetI(){
returnthis.i;
}
publicSocketgetClient(){
returnthis.Client;
}
publicvoidrun(){
try{
theInputStream=newBufferedReader(newInputStreamReader(Client
.getInputStream()));
theOutputStream=newPrintStream(Client.getOutputStream());
while(true){
readin=theInputStream.readLine();
chat.ta.append(readin+"\n");
}
}catch(SocketExceptione){
chat.ta.append("連線中斷!\n");
//設置組件可用性
chat.clientBtn.setEnabled(true);
chat.serverBtn.setEnabled(true);
chat.tfaddress.setEnabled(true);
chat.tfport.setEnabled(true);
try{
i--;
skt.close();
Client.close();
}catch(IOExceptionerr){
chat.ta.append(err.toString());
}
}catch(IOExceptione){
chat.ta.append(e.toString());
}
}
publicvoiddataout(Stringdata){
theOutputStream.println(data);
}}2.客戶端客戶端主要是使用Socket類,該類是JAVA實現網絡編程重要的基礎類,實現程序間雙向的面向連接的通信。調用publicSocket(Stringhost,intport)方法設定IP和端口。建好連接后,用戶通過得到Socket的輸入輸出流對象后,利用流的方法實現數據的傳輸。調用publicInputStreamgetInputStream()和publicOutputStreamgetOutputStream()方法,分別得到Socket對象的輸入輸出流;具體實現代碼如下:packagenupt.java.socket;import.*;importjava.io.*;importjavax.swing.Timer;publicclassClientextendsThread{
Socketskt;
//用于客戶端的連接
InetAddresshost;
//主機地址
intport;
//端口號
BufferedReadertheInputStream;
PrintStreamtheOutputStream;
Stringreadin;
Facechat;
publicClient(Stringip,intp,Facechat){
try{
host=InetAddress.getByName(ip);
//獲取IP地址
port=p;
//獲取端口號
this.chat=chat;
}catch(IOExceptione){
chat.ta.append(e.toString());
}
}
publicvoidrun(){
try{
chat.ta.append("準備連線,稍后!");
skt=newSocket(host,port);
//新建Socket對象
chat.ta.append("成功\n");
//緩沖區(qū)末尾添加字符串
theInputStream=newBufferedReader(newInputStreamReader(skt.getInputStream()));
theOutputStream=newPrintStream(skt.getOutputStream());
while(true){
readin=theInputStream.readLine();
chat.ta.append(readin+"\n");
}
}catch(SocketExceptione){
chat.ta.append("未連上!\n");
chat.clientBtn.setEnabled(true);
chat.serverBtn.setEnabled(true);
chat.tfaddress.setEnabled(true);
chat.tfport.setEnabled(true);
try{
skt.close();
}catch(IOExceptionerr){
chat.ta.append(err.toString());
}
}catch(IOExceptione){
chat.ta.append(e.toString());
}
}
publicvoiddataout(Stringdata){
theOutputStream.println(data);
}}3.用戶圖形界面該部分主要是完成界面的初始化,合理布局組件,方便用戶交互。主要是JAVA按鈕,文本域,標簽,布局管理器的使用。主要處理了鍵盤Enter消息接受,下面是實現代碼:packagenupt.java.socket;importjava.awt.*;importjava.awt.event.*;publicclassFaceextendsFrame{
privatestaticfinallongserialVersionUID=1L;
ButtonclientBtn,serverBtn;
TextAreata;
TextFieldtfaddress,tfport,tftype;
Labellbl1,lbl2,lbl3;
intport;
Clientclient;
Serverserver;
booleaniamserver;
staticFacefrm;
publicFace(){
//實例化組件
clientBtn=newButton("客戶端");
serverBtn=newButton("服務器");
ta=newTextArea("",10,50,TextArea.SCROLLBARS_BOTH);
lbl1=newLabel("IP地址:");
tfaddress=newTextField("04",10);
lbl2=newLabel("端口:");
tfport=newTextField("8080");
lbl3=newLabel("發(fā)送內容:");
tftype=newTextField(40);
tftype.addKeyListener(newTFListener());
ta.setEditable(false);
//向容器中加入以上組件
setLayout(new
FlowLayout());
add(lbl1);
add(tfaddress);
add(lbl2);
add(tfport);
add(clientBtn);
add(serverBtn);
add(ta);
add(lbl3);
add(tftype);
//設置格式
setLocation(400,250);
//窗口顯示再屏幕的位置坐標
setSize(400,300);
//設置窗體大小
setTitle("基于Socket和多線程編程的聊天程序");
this.setVisible(true);
//設置窗體可見
//事件響應
clientBtn.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
port=Integer.parseInt(tfport.getText());
client=newClient(tfaddress.getText(),port,frm);
client.start();
tfaddress.setEnabled(false);
tfport.setEnabled(false);
serverBtn.setEnabled(false);
clientBtn.setEnabled(false);
}
});
serverBtn.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
port=Integer.parseInt(tfport.getText());
server=newServer(port,frm);
server.start();
iamserver=true;
tfaddress.setText("成為服務器");
tfaddress.setEnabled(false);
tfport.setEnabled(false);
serverBtn.setEnabled(false);
clientBtn.setEnabled(false);
}
});
addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);
}
});
}
publicstaticvoidmain(String[]args){
//主方法
//TODOAuto-generatedmethodstub
frm=newFace();
}
privateclassTFListenerimplementsKeyListener{
publicvoidkeyPressed(KeyEvente){
if(e.getKeyCode()==KeyEvent.VK_ENTER){//按Enter輸出顯示聊天內容
ta.append(">"+tftype.getText()+"\n");
if(iamserver)
server.dataout(tftype.getText());
else
client.dataout(tftype.getText());
tftype.setText("");
}
}
publicvoidkeyTyped(KeyEvente){
}
publicvoidkeyReleased(KeyEvente){
}
}}1.程序運行初始化界面如下:2.輸入發(fā)送的聊天內容后的測試效果:通過以上測試分析可知,程序很好地完成了課題的要求,運行結果正確,利用JAVA語言的異常處理機制很好地處理了各種異常,使得程序的性能變得相對穩(wěn)定,界面舒適易用,可以滿足基本聊天需要!一、調試過程中的問題程序的調試相對程序的編碼復雜多了,需要很大的精力才能做好。1.問題的描述(1)JAVA語言的基本知識已具備,但是Socket網絡方面還不是很了解,花了不少工夫。Socket(套接字),用于描述IP地址和端口,通信
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 產品攝影拍攝合同范本
- 健身房私教合同范本
- 2025年度新型綠色建筑租賃合同范本
- 出兌房屋合同范例
- ppp合同范例實例
- 保管勞動合同范例
- 2025年度城市綜合體規(guī)劃設計咨詢合同
- 廣東省x景區(qū)旅游開發(fā)項目可行性研究報告
- 2025年中國新風量檢測儀行業(yè)市場發(fā)展前景及發(fā)展趨勢與投資戰(zhàn)略研究報告
- 買債權居間合同范本
- 綠城桃李春風推廣方案
- 對使用林地的監(jiān)管事中事后監(jiān)督管理
- 體質健康概論
- 檔案管理流程優(yōu)化與效率提升
- 2023高考語文實用類文本閱讀-新聞、通訊、訪談(含答案)
- 人工智能在商場應用
- (完整word版)大格子作文紙模板(帶字數統(tǒng)計)
- 高考語文復習:小說閱讀主觀題題型探究-解讀《理水》
- revit簡單小別墅教程
- 第二章 第一節(jié) CT設備基本運行條件
- 藍印花布鑒賞課件
評論
0/150
提交評論