哈尔滨网站制作方案最有效的免费推广方法
DAY13.2 Java核心基础
多线程下的网络编程
基于单点连接的方式,一个服务端对应一个客户端,实际运行环境中是一个服务端需要对应多个客户端
创建ServerSocketNable类,多线程接收socket对象
public class ServerSocketNable implements Runnable {private Socket socket;public ServerSocketNable(Socket socket) {this.socket = socket;}@Overridepublic void run() {//接收消息InputStream inputStream = null;DataInputStream dataInputStream = null;try {inputStream = socket.getInputStream();dataInputStream = new DataInputStream(inputStream);String s = dataInputStream.readUTF();System.out.println(Thread.currentThread().getName() + "服务器接收到的消息:" + s);} catch (IOException e) {throw new RuntimeException(e);} finally {try {inputStream.close();dataInputStream.close();socket.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
创建ClientNable对象,实现给服务器发消息的任务
public class ClientNable implements Runnable {private Integer num;public ClientNable(Integer num) {this.num = num;}@Overridepublic void run() {// 创建一个Socket对象,需要指定服务器的IP地址和端口号OutputStream outputStream = null;DataOutputStream dataOutputStream = null;Socket socket = null;try {socket = new Socket("127.0.0.1", 8080);outputStream = socket.getOutputStream();dataOutputStream = new DataOutputStream(outputStream);dataOutputStream.writeUTF("你好,我是客户端:" + num);} catch (IOException e) {throw new RuntimeException(e);} finally {try {outputStream.close();dataOutputStream.close();socket.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
服务器启动
public static void main(String[] args) {Socket socket = null;try {ServerSocket serverSocket = new ServerSocket(8080);while (true) {socket = serverSocket.accept();ServerSocketNable serverSocketNable = new ServerSocketNable(socket);Thread thread = new Thread(serverSocketNable);thread.start();}} catch (IOException e) {throw new RuntimeException(e);} finally {try {socket.close();} catch (IOException e) {throw new RuntimeException(e);}}
}
客户端启动
public static void main(String[] args) {for (int i = 0; i < 100; i++) {Thread thread = new Thread(new ClientNable(i));thread.start();}
}
这样就实现了多线程收发的功能,效率更高,开发中使用更加常见
部分代码输出:
可以看见不是顺序执行的