java socket多线程使用-整理篇

来源:互联网 发布:淘宝店铺被恶意举报 编辑:程序博客网 时间:2024/06/05 14:14

使用多线程启动服务端

ServerSocket serverSocket = null;ExecutorService executorService = null;try {serverSocket = new ServerSocket(5678);executorService = Executors.newFixedThreadPool(5);while (true) {final Socket socket = serverSocket.accept();executorService.execute(new SocketThread(socket));}} catch (Exception e) {e.printStackTrace();}finally{try {if(serverSocket!=null)serverSocket.close();} catch (Exception e2) {e2.printStackTrace();}}

服务端线程类:SocketThread的run方法:

public void run() {System.out.println("接收到来自"+socket.getInetAddress()+":"+socket.getPort()+",的连接!");try {DataInputStream dis = new DataInputStream(socket.getInputStream());int readInt = dis.readInt();byte[] readData = new byte[readInt];dis.read(readData);System.out.println(new String(readData,"utf-8"));DataOutputStream dos = new DataOutputStream(socket.getOutputStream());byte[] outData = "OKOK".getBytes("utf-8");int writeInt = outData.length;dos.writeInt(writeInt);dos.write(outData);dos.flush();dis.close();dos.close();} catch (Exception e) {e.printStackTrace();}finally{try {if(socket!=null)socket.close();} catch (Exception e2) {e2.printStackTrace();}}System.out.println("来自"+socket.getInetAddress()+":"+socket.getPort()+",的连接处理完毕!");}


客户端的读写,其它和上面接收到监听后的读写差不多:

Socket socket=null;try {socket = new Socket(InetAddress.getLocalHost(), 5678);DataInputStream dis = new DataInputStream(socket.getInputStream());int readInt = dis.readInt();byte[] readData = new byte[readInt];dis.read(readData);System.out.println(new String(readData,"utf-8"));DataOutputStream dos = new DataOutputStream(socket.getOutputStream());byte[] outData = "OKOK".getBytes("utf-8");int writeInt = outData.length;dos.writeInt(writeInt);dos.write(outData);dos.flush();dis.close();dos.close();} catch (Exception e) {e.printStackTrace();}finally{try {if(socket!=null)socket.close();} catch (Exception e2) {e2.printStackTrace();}}


0 0
原创粉丝点击