端
的
信
息
流
服务器端
四.主要程序
源代码;主要程序源代码;
服务器端程序:importjava.net.*;importjava.io.*;importjava.util.*;/*聊天服务器端处理主类ChatServer*/publicclassChatServerimplementsRunnable{publicstaticfinalintPORT=1234;protectedServerSocketlisten;//定义服务器端套接字listenstaticVectorconnections;//向量类connections存放与服务器连接的客户线程列表Threadconnect;//定义服务器端线程//服务器构造初始化线程publicChatServer(){try{listen=newServerSocket(PORT);//使用本地IP地址创建一个服务器}catch(UnknownHostExceptione2){System.err.println("error:"+e2);}catch(IOExceptione){
System.err.println("error:"+e);System.exit(1);}connections=newVector(1000);connect=newThread(this);connect.start();//服务器端程序启动}//服务器main()初始化publicstaticvoidmain(Stringargs[]){newChatServer();System.out.println("ChatServerisstarting!......");
//服务器线程connect操作run方法}publicvoidrun(){try{while(true){//始终监听来自网络端口的信息Socketclient=listen.accept();//为每一个人分别启动一个客户端线程
FirstThreadft=newFirstThread(this,client);ft.setPriority(Thread.MIN_PRIORITY);ft.start();//客户端线程启动connections.addElement(ft);//将客户端线程加入向量列表中
}}catch(IOExceptione){System.err.println("error:"+e);System.exit(1);}}//向聊天室所有人员发送普通话语信息publicvoidbr
oadcast(Stringyaoshuode){inti;FirstThreadyou;for(i=0;i
}}//处理悄悄话,向特定人员发送悄悄话publicvoidbroadcast1(Stringyaoshuode){inti;Strings1,s2,s3;FirstThreadyou;s1=newString("PEOPLE");s2=newString(yaoshuode.substring(4));//悄悄地对为4个字符s3=s1.concat(s2);for(i=0;i }//客户端线程类FirstThreadclassFirstThreadextendsThread{protectedSocketclient;//line读取来自客户端的消息;name格式为:PEOPLE+名字+[性别]Stringline,name;protectedDataOutputStreamfirstout,out;//定义网络数据输出流protectedChatServerserver;protectedDataInputStreamin;//定义网络数据输出流
//FirstThread初始化线程publicFirstThread(ChatServerserver,Socketclient){this.server=server;this.client=client;try{in=newDataInputStream(client.getInputStream());out=newDataOutputStream(client.getOutputStream());firstout=newDataOutputStream(client.getOutputStream());}catch(IOExceptione){
try{server.connections.removeElement(this);client.close();}catch(IOExceptione2){System.err.println("有问题哦"+e);return;}}if(this.client==null){server.broadcast("QUIT"+this.name);this.name=null;}}publicvoidrun(){try{//客户端线程初始化运行读取服务端的已有聊天室人员列表信息inti;for(i=0;i