多线程server

/*聊天室程序服务器端程序
监听连接的客户端
接受某客户端输入然后广播
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
public class Server{
public Server(int port) throws IOException{
ServerSocket server=new ServerSocket(port);
//不断循环接受客户端的连接
while(true)
{
Socket conn=server.accept();
DataInputStream in=new DataInputStream(conn.getInputStream());
String who=in.readUTF();
System.out.print(“Client “+”(IP:”+conn.getInetAddress()+”)”+who+” enter!”+”\n”);
//每次监听到连接请求就创建一个线程
ServerHander cn=new ServerHander(who,conn);
cn.start();
}
}
public static void main(String args[])throws IOException{
new Server(9001);
}
}
class ServerHander extends Thread{
Socket socket;
DataInputStream in;
DataOutputStream out;
String who;
//保存所有的客户端对象
protected static Vector clientlist=new Vector();
public ServerHander(String name,Socket socket)throws IOException
{
this.who=name;
this.socket=socket;
in=new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out=new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
}
public void run(){
try{
clientlist.addElement(this);
sendallclient(“Welcome “+who+” entered”);
while(true)
{
String msg=in.readUTF();
sendallclient(who+” said: “+msg);
}
}
catch(IOException e)
{
System.out.println(“Client exit or error.”);
}
finally{
clientlist.removeElement(this);
sendallclient(who+” left !”);
try
{
socket.close();
}
catch(IOException ex)
{
System.out.println(“Connection has been closed”);
}
}
}
//给客户端传递信息
protected static void sendallclient(String msg)
{
synchronized(clientlist){
Enumeration allclients=clientlist.elements();
while(allclients.hasMoreElements())
{
ServerHander serh=allclients.nextElement();
try{
serh.out.writeUTF(msg);
serh.out.flush();
}
catch(IOException exc)
{
serh.interrupt();

                }
        }
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值