Socket 多线程简例

来源:互联网 发布:snmp监控linux 编辑:程序博客网 时间:2024/06/01 10:23

多线程服务端,单独线程处理客户端连接,多个客户端之间不会阻塞

服务器端:

public class Server {ServerSocket serverSocket;Socket socket;public Server() throws IOException {serverSocket = new ServerSocket(10086);while (true) {socket = serverSocket.accept();// 启动多线程处理 socketnew SocketHandler(socket).start();}}public static void main(String[] args) {try {new Server();} catch (IOException e) {e.printStackTrace();}}}

Socket多线程处理类:

public class SocketHandler extends Thread {private Socket socket;public SocketHandler(Socket socket) {this.socket = socket;}@Overridepublic void run() {try {accept(this.socket);} catch (IOException e) {e.printStackTrace();}}private void accept(Socket socket) throws IOException {BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));String msg = socketIn.readLine();System.out.println("Client: " + msg);socketIn.close();}}

客户端:

public class Client {Socket socket;public Client() throws UnknownHostException, IOException {// 连续发送while (true) {send();}}private void send() throws IOException {socket = new Socket("localhost", 10086);PrintWriter socketOut = new PrintWriter(socket.getOutputStream());System.out.print("Say: ");BufferedReader input = new BufferedReader(new InputStreamReader(System.in));socketOut.write(input.readLine());socketOut.close();}public static void main(String[] args) {try {new Client();} catch (IOException e) {e.printStackTrace();}}}