📄 firstthread.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//客户端线程类
class firstthread extends Thread{
protected Socket client;
//line读取来自客户端的消息;name格式为:PEOPLE 名字 性别
String line,name;
protected DataOutputStream firstout,out;//定义网络数据输出流
protected chatserverthree server;
protected DataInputStream in;//定义网络数据输出流
//firstthread初始化线程
public firstthread(chatserverthree server,Socket client){
this.server=server;
this.client=client;
try{
in=new DataInputStream(client.getInputStream());
out=new DataOutputStream(client.getOutputStream());
}
catch(IOException e)
{
try{
server.connections.removeElement(this);
client.close();
}
catch(IOException e2)
{
System.err.println("有问题哦:"+e);
return;
}
}
if(this.client==null)
{
server.broadcast("QUIT"+this.name);
this.name=null;
}
}
public void run(){
try{
//客户端线程初始化运行读取服务器端的已有聊天室人员列表信息
for(int i=0;i<server.connections.size();i++)
{
firstthread c=(firstthread)(server.connections.elementAt(i));
if(c.name!=null)
{
try{
firstout.writeUTF(c.name+"*");
}
catch(IOException e){}
}
}
}
catch(ArrayIndexOutOfBoundsException e){}
catch(NullPointerException e){}
//客户端线程始终在监听的操作方法
try{
while(true)
{
line=in.readUTF();// line读取来自客户端线程的信息
//线路信息前端为PEOPLE表明有新人进入
if(line.startsWith("PEOPLE"))
{
try //获取当前对象的线程
{
firstthread d=(firstthread)(server.connections.elementAt
(server.connections.indexOf(this)));
if(d.name==null)
{
d.name=line;}
//有人在一个窗口中换用另一个名字登陆
else if(d.name!=null)
{
//写入OUIT+PEOPLE+名字+性别
server.broadcast("OUIT"+this.name);
d.name=line;//使原来的人离开
}
}
catch(ArrayIndexOutOfBoundsException e){}
catch(NullPointerException e){}
finally{server.broadcast(line);}
//向聊天室所有人员发送有人进入聊天室信息
}
//线程信息前端为QUIT表明有人离开了
else if(line.startsWith("QUIT"))
{
server.broadcast("QUIT"+this.name);
server.connections.removeElement(this);
this.in.close();
this.out.close();
this.firstout.close();//关闭输入输出流
this.client.close();
this.yield();
}
//线路信息前端为MSG表明接受到的是普通聊天话语信息
else if(line.startsWith("MSG"))
{
server.broadcast(line);
}
//线路信息前端为“悄悄地对”表明接收到悄悄话
else if(line.startsWith("secret"))
{//悄悄话在自己的文本区显示
this.out.writeUTF(line);
//悄悄话在对方的文本区显示
server.broadcast1(line);
}
//线路信息前端为newlist表明得到客户端刷新列表的请求
else if(line.startsWith("newlist"))
{
try{
for(int i=0;i<server.connections.size();i++)
{
firstthread c=(firstthread)(server.connections.elementAt(i));
if(c.name!=null)
{
try{
//name格式为:PEOPLE+名字+性别
firstout.writeUTF(c.name+"*");
}
catch(IOException e) {}
}
}
}
catch(ArrayIndexOutOfBoundsException e){}
catch(NullPointerException e){}
}
}
}
catch(IOException e)
{
server.connections.removeElement(this);
}
catch(NullPointerException e)
{
server.connections.removeElement(this);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -