Socket和多线程编程的聊天程序实现_第1页
Socket和多线程编程的聊天程序实现_第2页
Socket和多线程编程的聊天程序实现_第3页
Socket和多线程编程的聊天程序实现_第4页
Socket和多线程编程的聊天程序实现_第5页
已阅读5页,还剩8页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

滨江学院课程设计任务书学年学期2012-2013学年第二学期

课程名称用socket实现聊天程序 院系计算机系 专业计科 姓名周洲指导教师 朱节中二O一三年七月七日用Socket的编程机制实现聊天程序10计科周洲20092308065摘要:Socket是基于TCP/IP的网络上运行的两个程序间双向通讯的一种连接机制,包中包含Socket类,用以快速地开发网络通信程序。通过实例模型探讨基于Java的Socket通信程序的一般结构。对开发一般性的通信软件,有一定的参考价值。关键词:Java;网络;SocketSocketProgrammingBasedonTCP/IPinJavaAbstract:Socketisoneofthetwo-waycommunication'sendbetweentwoproceduresthatareoperatedonthenetworkbasedonTCP/IP.JbagincludesSockets,whichisusedtodevelopthenetworkcommunicationprocedurefast.ThispaperprobesintothegeneralstructurebasedonSocketcommunicationprocedureofJavathroughtheinstancemodel.Thegeneralcommunicationsoftwarecanbedevelopedbasedonthisone,sothereiscertainreferencevalue.Keywords:ava;network;Socket;communication一、课题内容和要求1.课题内容基于Socket和多线程编程的聊天程序实现2.课题要求网络聊天程序设计非常复杂,允许多个人同时聊天更加需要多线程技术的支持,请实现一个简单的多线程网络聊天程序模拟。二、设计思路分析1.在网络越来越发达的今天,人们对网络的依赖越来越强,网络聊天已经成了许多人生活中必不可少的一部分,基于这样的需求,出现了许多网络聊天通信工具,像QQ,MSN等等,但是人们已经不再满足于单一的两个人之间的聊天,而是对多人同时聊天产生了兴趣,于是出现了网络聊天室,不同地方的人可以在那个虚拟的聊天室里面热烈聊天。基于这样的想法,我们用JAVA设计一个多人同时聊天的小程序,用Socket编程实现网络通讯,面向连接的,采用多线程的实现技术。2.在程序中,可以设置加入连接的最大数目,通过更改IP地址和端口号,成为不同的客户端,与服务器端连接,进行多用户聊天。3.为方便用户交互,我们采用图形化的用户界面。实现了好友添加,消息收发、显示等基本功能。三、概要设计该网络聊天程序大致分为三个主要部分:客户端、服务器端和用户图形界面。各个部分的初步设计思想、流程及存储结构如下:1.程序整体框架:主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。

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");

//缓冲区末尾添加字符串

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("发送内容:");

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.输入发送的聊天内容后的测试效果:通过以上测试分析可知,程序很好地完成了课题的要求,运行结果正确,利用JAVA语言的异常处理机制很好地处理了各种异常,使得程序的性能变得相对稳定,界面舒适易用,可以满足基本聊天需要!一、调试过程中的问题程序的调试相对程序的编码复杂多了,需要很大的精力才能做好。1.问题的描述(1)JAVA语言的基本知识已具备,但是Socket网络方面还不是很了解,花了不少工夫。Socket(套接字),用于描述IP地址和端口,通信

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论