📄 chatserverthree.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
//聊天室服务器端处理主类
public class chatserverthree implements Runnable{
public static final int PORT=1234;
protected ServerSocket listen;//定义服务器端套接字lisnten
static Vector connections;//向量类conections存放与服务器连接的客户线程列表
Thread connect;//定义服务器端线程
//服务器构造初始化线程
public chatserverthree(){
try{
listen=new ServerSocket(PORT);}//使用本地IP地址创建一个服务器
catch(UnknownHostException e2){
System.err.println("erro:"+e2);
}
catch(IOException e)
{
System.err.println("erro:"+e);
System.exit(1);
}
connections=new Vector(1000);
connect=new Thread(this);
connect.start();//服务器线程驱动
}
//初始化
public static void main(String[] args){
new chatserverthree();
System.out.println("Chat Server is starting!...");
}
//服务器线程connect操作run方法
public void run(){
try{
while(true)//始终监听来自网络端口的信息
{
Socket client=listen.accept();
//为每一个人分别驱动一个客户端线程
firstthread f = new firstthread(this,client);
f.setPriority(Thread.MIN_PRIORITY);
f.start();//客户端线程驱动
connections.addElement(f);//将客户端线程加入向量列表中
}
}
catch(IOException e)
{
System.err.println("erro:"+e);
System.exit(1);
}
}
//向聊天室所有人员发送普通话信息
public void broadcast(String msg)
{
int i; firstthread you;
for(i=0;i<connections.size();i++)
{
you=(firstthread)connections.elementAt(i);
try{
you.out.writeUTF(msg);}
catch(IOException e){}
}
}
//处理悄悄话,向特定人员发送悄悄话
public void broadcast1(String msg){
int i;String s1,s2,s3;
firstthread you;
s1=new String("PEOPLE");
s2=new String(msg.substring(4));//悄悄的对为4个字符
s3=s1.concat(s2);
for(i=0;i<connections.size();i++)
{
you=(firstthread)connections.elementAt(i);
if(s3.startsWith(you.name))//name格式为:PEOPLE+名字+[性别}
{
try{
you.out.writeUTF(msg);
}
catch(IOException e) {}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -