1.ServerSocket进行多线程接收
package com.yh.chat; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ChatServerSocket { public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket serversocket = null; Socket socket = null; try { serversocket = new ServerSocket(5005); while (true) { socket = serversocket.accept(); ChatAcceptSocket accept = new ChatAcceptSocket(socket); accept.start(); } // 发送信息 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.yh.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; public class ChatAcceptSocket extends Thread { private Socket socket; public ChatAcceptSocket(){} public ChatAcceptSocket(Socket socket){ this.socket=socket; } @Override public void run() { // TODO Auto-generated method stub InputStream is = null; BufferedReader br = null; // 接收信息 try { is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String info = ""; while ((info = br.readLine()) != null) { OutputStream os = socket.getOutputStream(); byte[] replys = info.getBytes(); System.out.println("广播:"+info); os.write(replys); os.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2.客户端进行连接(代码省略,参考:流式套接字:基于TCP协议的Socket网络编程(案例1))
这里ServerSocket进行的广播仅限当前线程的中的socket,不会给其他线程的socket发送数据。