- package test;
- import java.io.*;
- import java.net.*;
- public class MultiServer {
- public MultiServer() throws IOException {
- ServerSocket ss=new ServerSocket(7777);
- while(true){
- Socket socket=ss.accept();
- new DealMessage(socket).start();
- }
- }
- public static void main(String[] args) {
- try {
- new MultiServer();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- class DealMessage extends Thread {
- private Socket socket;
- private InputStream in;
- private OutputStream out;
- public DealMessage(Socket s) throws IOException {
- this.socket = s;
- this.in = socket.getInputStream();
- this.out = socket.getOutputStream();
- }
- public void run() {
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(in));
- System.out.println("you IP is: " + socket.getInetAddress()+":"+socket.getPort());
- System.out.println("you enter is: " + br.readLine());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void finalize() throws IOException {
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
- }
- }
服务器响应多个Client的Socket请求
最新推荐文章于 2022-04-22 09:18:04 发布
本文介绍了一个基于Java实现的简单多线程网络服务器代码示例。该服务器能够监听7777端口并处理客户端连接请求,为每个连接创建一个新的线程来处理消息。通过该示例可以学习如何使用ServerSocket和Socket类建立网络通信。
摘要由CSDN通过智能技术生成