Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的多线程客户机-服务器聊天应用程序_Java_Multithreading_Client Server - Fatal编程技术网

java中的多线程客户机-服务器聊天应用程序

java中的多线程客户机-服务器聊天应用程序,java,multithreading,client-server,Java,Multithreading,Client Server,我正在尝试用java编写多线程客户机-服务器聊天应用程序。 我只想创建两个线程,从每个线程发送一些数字,然后从服务器获取相同的数字。但有些地方出了问题 这是客户端代码 import java.io.*; import java.net.*; public class Client implements Runnable{ private Socket clientSocket = null; private DataInputStream input = null;

我正在尝试用java编写多线程客户机-服务器聊天应用程序。 我只想创建两个线程,从每个线程发送一些数字,然后从服务器获取相同的数字。但有些地方出了问题

这是客户端代码

import java.io.*;
import java.net.*;

public class Client implements Runnable{

    private Socket clientSocket = null;
    private DataInputStream input = null;
    private PrintStream output = null;
    private DataInputStream inputLine = null;
    private int id;

    public Client(int id){
        this.id = id;
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        System.out.println("The client started. Type any text. To quit it type 'Ok'.");

        Client a = new Client(1);
        Thread one = new Thread(a);

        Client b = new Client(2);
        Thread two = new Thread(b);
        one.start();
        two.start();  

        one.join();
        two.join();               

    }

    public void run() {
        System.out.println("hi from thread" + id);
        try {
            clientSocket = new Socket("localhost", 4444);
            output = new PrintStream(clientSocket.getOutputStream());
            input = new DataInputStream(clientSocket.getInputStream());
            inputLine = new DataInputStream(new BufferedInputStream(System.in));
        } 
        catch( IOException e){
            System.out.println(e);
        }
        String responseLine;
        try{      
            for(int i = 0; i < 10; i++){
                output.println( id + " " + i);
                System.out.println("sended:" + id + " " + i);
                responseLine = input.readLine();
                System.out.println("received: " + responseLine);
            }
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }

}
import java.io.*;
导入java.net。*;
公共类客户端实现可运行{
私有套接字clientSocket=null;
私有数据输入流输入=null;
私有PrintStream输出=null;
私有DataInputStream inputLine=null;
私有int-id;
公共客户端(int-id){
this.id=id;
}
公共静态void main(字符串[]args)引发IOException、InterruptedException{
System.out.println(“客户端已启动。请键入任何文本。要退出,请键入“Ok”。”;
客户a=新客户(1);
螺纹1=新螺纹(a);
客户b=新客户(2);
螺纹2=新螺纹(b);
一、启动();
二、启动();
一、join();
二、join();
}
公开募捐{
System.out.println(“来自线程的hi”+id);
试一试{
clientSocket=新套接字(“localhost”,4444);
输出=新的打印流(clientSocket.getOutputStream());
input=新的DataInputStream(clientSocket.getInputStream());
inputLine=新的DataInputStream(新的BufferedInputStream(System.in));
} 
捕获(IOE异常){
系统输出打印ln(e);
}
弦响应线;
试试{
对于(int i=0;i<10;i++){
输出.println(id+“”+i);
System.out.println(“发送:+id+”+i);
responseLine=input.readLine();
System.out.println(“接收:+响应线”);
}
}
捕获(IOE异常){
系统输出打印ln(e);
}
}
}
和服务器代码

import java.io.*;
import java.net.*;

public class Server implements Runnable{
    private static ServerSocket MyService = null;        
    private  DataInputStream input = null;
    private  PrintStream  output = null;
    private  String line;
    private static Socket serviceSocket = null;

    public static void main(String[] args) throws IOException {


        try{
            MyService = new ServerSocket(4444);
            if(args.length > 0){
                MyService = new ServerSocket(Integer.parseInt(args[0]));
            }
        } 
        catch( IOException e){
            System.out.println("Couldn't linputten to port " + (args.length > 0 ? Integer.parseInt(args[0]) : 4444));
        }

        System.out.println("The server started. To stop it press <CTRL><C>.");
        while(true){
            try {
                serviceSocket = MyService.accept();            
                new Thread(new Server()).start(); 
                System.out.println("CREATED");
            }
            catch (IOException e) {
                System.out.println("can't accept");
            }
        }

    }

    public void run(){
        try {    
            input = new DataInputStream(serviceSocket.getInputStream());
            output = new PrintStream(serviceSocket.getOutputStream());
            while (true) {
                line = input.readLine();
                System.out.println("from client:" + line+"\n");
                output.println("From server: " + line+"\n");

            }

        }
        catch(IOException e) {
            System.out.println(e);
        }
    }

}
import java.io.*;
导入java.net。*;
公共类服务器实现可运行{
私有静态服务器套接字MyService=null;
私有数据输入流输入=null;
私有PrintStream输出=null;
专用字符串线;
私有静态套接字serviceSocket=null;
公共静态void main(字符串[]args)引发IOException{
试一试{
MyService=newserversocket(4444);
如果(args.length>0){
MyService=newserversocket(Integer.parseInt(args[0]);
}
} 
捕获(IOE异常){
System.out.println(“无法将linputten连接到端口”+(args.length>0?Integer.parseInt(args[0]):4444));
}
System.out.println(“服务器已启动。要停止它,请按“);
while(true){
试一试{
serviceSocket=MyService.accept();
新线程(新服务器()).start();
System.out.println(“已创建”);
}
捕获(IOE异常){
System.out.println(“无法接受”);
}
}
}
公开募捐{
试试{
输入=新的DataInputStream(serviceSocket.getInputStream());
输出=新的打印流(serviceSocket.getOutputStream());
while(true){
line=input.readLine();
System.out.println(“来自客户端:“+line+”\n”);
output.println(“来自服务器:“+line+”\n”);
}
}
捕获(IOE异常){
系统输出打印ln(e);
}
}
}

在服务器端,每个新客户机都应该在单独的
线程上,您正在为您的
服务套接字分配一个
新的
套接字
,这样您就基本上忽略了以前连接的客户机

您可以为刚刚连接的客户端启动
新服务器
,而不是启动
线程
。您应该为连接的每个客户端创建一个
新套接字
,并在
新线程
上运行它,而不是在客户端连接后启动
新服务器

更新

以下是基本多客户端服务器的示例:

服务器代码由几个类组成:

// Server.java
public class Server {

    private ServerSocket        socket;
    private ConnectionListener  connectionListener;

    // temp
    private List<Client> clientList = new ArrayList<Client>();
    // temp end

    public Server(int port) {
        try {
            socket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }

        connectionListener = new ConnectionListener(this);
    }

    public void start() throws IOException {

        connectionListener.start();

        // temp will move to a Thread later
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String input;
        while (((input = stdIn.readLine()) != null) && connectionListener.isAlive()) {
            if (input.equalsIgnoreCase("exit")) {
                break;
            } else {
                for (int i = 0; i < input.length(); i++)
                    System.out.print("\b");
                System.out.println("Admin: " + input);
                for (Client c : clientList) {
                    c.send("Admin: " + input);
                }
            }

        }
        stop();
        // temp end
    }

    public void stop() {

        connectionListener.stop();
        for (Client c : clientList) {
            c.closeSession();
        }

        System.out.println("Server terminated!");
    }

    public synchronized void addConnection(Connection connection) {

        Client c = new Client(connection, clientList);
        clientList.add(c);
        c.startSession();
        System.out.println("Client connected");
    }

    public ServerSocket getSocket() {

        return socket;
    }

    public static void main(String[] args) throws IOException {

        int port;
        if (args.length > 0)
            port = Integer.parseInt(args[0]);
        else
            port = 4444;
        Server s = new Server(port);
        s.start();
    }

}
// Client.java
public class Client {

    public static void main(String[] args) {

        String host;
        if (args.length > 0)
            host = args[0];
        else
            host = "localhost";

        int port;
        if (args.length > 1)
            port = Integer.parseInt(args[1]);
        else
            port = 4444;

        try (Socket socket = new Socket(host, port);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            Thread input = new Thread(() -> {
                String msg;
                try {
                    while ((msg = in.readLine()) != null) {
                        System.out.println(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            input.start();

            String userName = "User" + ((int) (Math.random() * 200));
            String msg;
            try {
                while ((msg = stdIn.readLine()) != null) {
                    for (int i = 0; i < msg.length(); i++)
                        System.out.print("\b");
                    out.write(userName + ": " + msg + "\n");
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}


//Client.java
/*
*这仍然是服务器端,即连接的客户端的处理程序
*/
公共类客户端实现可运行{
公共静态最终长空闲时间=10;
专用连接;
私有布尔活着;
私有线程t;
私人名单客户名单;
公共客户端(连接、列表客户端列表){
这个连接=连接;
this.clientList=clientList;
活着=假;
}
公共同步的void startSession(){
如果(活着)
返回;
活着=真;
t=新螺纹(本螺纹);
t、 start();
}
公共同步的void closeSession(){
如果(!活着)
返回;
活着=假;
试一试{
connection.close();
t、 join();
}捕捉(中断异常e){
e、 printStackTrace();
}
}
公开募捐{
while(connection.isAlive()){
字符串in=connection.read();
if(in!=null){
系统输出打印项次(输入);
用于(客户端c:clientList){
c、 送(进来);
}
}否则{
试一试{
线程睡眠(空闲时间);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
}
}
公共无效发送(字符串消息){
连接。写入(msg+“\n”);
连接。flush();
}
}
和客户端示例:

// Server.java
public class Server {

    private ServerSocket        socket;
    private ConnectionListener  connectionListener;

    // temp
    private List<Client> clientList = new ArrayList<Client>();
    // temp end

    public Server(int port) {
        try {
            socket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }

        connectionListener = new ConnectionListener(this);
    }

    public void start() throws IOException {

        connectionListener.start();

        // temp will move to a Thread later
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String input;
        while (((input = stdIn.readLine()) != null) && connectionListener.isAlive()) {
            if (input.equalsIgnoreCase("exit")) {
                break;
            } else {
                for (int i = 0; i < input.length(); i++)
                    System.out.print("\b");
                System.out.println("Admin: " + input);
                for (Client c : clientList) {
                    c.send("Admin: " + input);
                }
            }

        }
        stop();
        // temp end
    }

    public void stop() {

        connectionListener.stop();
        for (Client c : clientList) {
            c.closeSession();
        }

        System.out.println("Server terminated!");
    }

    public synchronized void addConnection(Connection connection) {

        Client c = new Client(connection, clientList);
        clientList.add(c);
        c.startSession();
        System.out.println("Client connected");
    }

    public ServerSocket getSocket() {

        return socket;
    }

    public static void main(String[] args) throws IOException {

        int port;
        if (args.length > 0)
            port = Integer.parseInt(args[0]);
        else
            port = 4444;
        Server s = new Server(port);
        s.start();
    }

}
// Client.java
public class Client {

    public static void main(String[] args) {

        String host;
        if (args.length > 0)
            host = args[0];
        else
            host = "localhost";

        int port;
        if (args.length > 1)
            port = Integer.parseInt(args[1]);
        else
            port = 4444;

        try (Socket socket = new Socket(host, port);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            Thread input = new Thread(() -> {
                String msg;
                try {
                    while ((msg = in.readLine()) != null) {
                        System.out.println(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            input.start();

            String userName = "User" + ((int) (Math.random() * 200));
            String msg;
            try {
                while ((msg = stdIn.readLine()) != null) {
                    for (int i = 0; i < msg.length(); i++)
                        System.out.print("\b");
                    out.write(userName + ": " + msg + "\n");
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
//Client.java
公共类客户端{
公共静态void main(字符串[]args){
字符串主机;
如果(args.length>0)
// Client.java
public class Client {

    public static void main(String[] args) {

        String host;
        if (args.length > 0)
            host = args[0];
        else
            host = "localhost";

        int port;
        if (args.length > 1)
            port = Integer.parseInt(args[1]);
        else
            port = 4444;

        try (Socket socket = new Socket(host, port);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            Thread input = new Thread(() -> {
                String msg;
                try {
                    while ((msg = in.readLine()) != null) {
                        System.out.println(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            input.start();

            String userName = "User" + ((int) (Math.random() * 200));
            String msg;
            try {
                while ((msg = stdIn.readLine()) != null) {
                    for (int i = 0; i < msg.length(); i++)
                        System.out.print("\b");
                    out.write(userName + ": " + msg + "\n");
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}