Java基础之使用多线程处理多客户端请求
Myserver2.java:
package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Myserver2 { public static void main(String[] args) throws IOException{ try { ServerSocket serverSocket = new ServerSocket(8888); while(true){ Socket socket = serverSocket.accept(); ServerThread serverThread = new ServerThread(socket); serverThread.start(); } } catch (Exception e) { // TODO: handle exception } } }
ServerThread.java:
package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.Socket; public class ServerThread extends Thread{ Socket socket ; public ServerThread(Socket socket){ this.socket = socket; } @Override public void run() { try { InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String info = null; while((info = reader.readLine())!=null){ System.out.println("I am server! 接收到的客户端消息:"+info); } socket.shutdownInput(); OutputStream out = socket.getOutputStream(); out.write("已收到!!!...".getBytes()); socket.shutdownOutput(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Myclient1.java:
package com.example.demo; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class Myclient { public static void main(String[] args) { try { Socket socket = new Socket("localhost",8888); System.out.println("客户端1启动"); OutputStream out = socket.getOutputStream(); out.write("hello socket!".getBytes()); socket.shutdownOutput(); InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String info = null; while((info = reader.readLine())!=null){ System.out.println("I am client1! 接收到的服务端端消息:"+info); } socket.shutdownInput(); } catch (Exception e) { // TODO: handle exception } } }
多创建几个client。运行看结果: