Java多线程Socket在控制台输出的多人聊天室编程
服务器端代码
1 import java.io.IOException; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 import java.util.ArrayList; 5 6 public class Server { 7 8 private static ArrayList<Socket> list = new ArrayList<Socket>(); 9 public static void main(String[] args) throws IOException { 10 ServerSocket server = new ServerSocket(9999); 11 while(true){ 12 Socket socket = server.accept(); 13 list.add(socket); 14 new ServerThread(socket,list).start();; 15 } 16 17 } 18 19 20 21 }
客户端代码
1 import java.io.IOException; 2 import java.net.Socket; 3 import java.net.UnknownHostException; 4 5 public class Client { 6 7 public static void main(String[] args) throws UnknownHostException, IOException { 8 Socket socket = new Socket("127.0.0.1",9999); 9 new ThreadWriter(socket).start(); 10 new ThreadReader(socket).start(); 11 } 12 13 }
服务器处理socket的多线程
1 import java.io.IOException; 2 import java.io.InputStream; 3 import java.io.OutputStream; 4 import java.net.Socket; 5 import java.util.ArrayList; 6 7 public class ServerThread extends Thread { 8 9 Socket socket; 10 ArrayList<Socket> list; 11 InputStream is; 12 OutputStream os; 13 public ServerThread(Socket socket, ArrayList<Socket> list) { 14 this.socket = socket; 15 this.list = list; 16 } 17 18 @Override 19 public void run() { 20 try { 21 while(true){ 22 is = socket.getInputStream(); 23 byte[] b = new byte[1024]; 24 int len = is.read(b); 25 String str = new String(b,0,len); 26 System.out.println(str); 27 for(Socket socket:list){ 28 os = socket.getOutputStream(); 29 os.write(str.getBytes()); 30 } 31 } 32 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 } 37 38 }
读取客户端输入流多线程代码
1 import java.io.IOException; 2 import java.io.InputStream; 3 import java.net.Socket; 4 5 public class ThreadReader extends Thread { 6 7 Socket socket; 8 public ThreadReader(Socket socket) { 9 this.socket = socket; 10 } 11 12 @Override 13 public void run() { 14 try { 15 while(true){ 16 17 InputStream is = socket.getInputStream(); 18 byte[] b = new byte[1024]; 19 int len = is.read(b); 20 String str = new String(b,0,len); 21 System.out.println(str); 22 } 23 } catch (IOException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 } 28 29 }
客户端发送数据多线程代码
1 import java.io.IOException; 2 import java.io.OutputStream; 3 import java.net.Socket; 4 import java.util.Scanner; 5 6 public class ThreadWriter extends Thread { 7 8 Socket socket; 9 public ThreadWriter(Socket socket) { 10 this.socket = socket; 11 } 12 13 @Override 14 public void run() { 15 try { 16 Scanner sc = new Scanner(System.in); 17 while(true){ 18 String str = sc.next(); 19 OutputStream os = socket.getOutputStream(); 20 os.write(str.getBytes()); 21 } 22 } catch (IOException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 28 }