Socket多线程连接,可单播收发信息

public class more implements Runnable{
private static ServerSocket serverSocket=null;
private  Socket Client=null;
private static int PORT=1234;//服务器端口号
private  BufferedReader buffRead=null;
private static  PrintWriter printWriter=null;
private Thread thread=null;
private static ArrayList<Socket>Socketlist=new ArrayList<Socket>();
more(){
thread=new Thread(this);
}
@Override
public void run() {
// TODO Auto-generated method stub
//阻塞accept,接收到客户端连接
try {
Client=serverSocket.accept();
Socketlist.add(Client);
//System.out.println(Socketlist.size());
System.out.println("list= "+Socketlist.get(Socketlist.size()-1).getInetAddress());
System.out.println("有客户端连接:"+Client.getInetAddress()+" "+Client.getPort());
more more1=new more();
more1.thread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
buffRead=new BufferedReader(new InputStreamReader(Client.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
printWriter=new PrintWriter(Client.getOutputStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
String context=buffRead.readLine();
System.out.println("服务器接收的数据 "+context);
printWriter.write("I Received");
printWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
more Test=new more();
//启动服务器,构造一个ServerSocket
// 操作系统不允许服务器绑定到 1-1023 之间的端口
  //如果把参数 port 设为 0, 表示由操作系统来为服务器分配一个任意可用的端口
try {
 serverSocket=new ServerSocket(PORT);
 System.out.println("服务器启动");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("服务器已启动,请勿重复创建");
}
Test.thread.start();
while(true){
Scanner scanner=new Scanner(System.in);
if (scanner!=null) {
int string=scanner.nextInt();
System.out.println("请输入字符:\t");
if (string>=0 && string <Socketlist.size()) {
try {
printWriter=new PrintWriter(Socketlist.get(string).getOutputStream());
Scanner scanner1=new Scanner(System.in);
String string2=scanner1.nextLine();
printWriter.write(string2);
printWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}  
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值