java服务器仅从1个客户端接收,而不是从第2个接收

时间:2015-11-13 09:58:20

标签: java sockets server client chat

美好的一天,我正在尝试创建一个客户端/服务器聊天,第一个客户端向服务器发送消息,服务器将消息发送到客户端2,反之亦然,但服务器只是从第一个客户端接收而不是从第二。 而且,我如何从客户端1发送消息到2&反之亦然

package s;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client 
{

public static void main(String[] args) throws IOException, Throwable 
{
    Socket s;
    BufferedReader in;
    PrintWriter out;
    Scanner sc = new Scanner(System.in);
    s = new Socket(InetAddress.getLocalHost(),9000);
    System.out.println("Connection pending");
    in = new BufferedReader (new InputStreamReader(s.getInputStream()));
    out = new PrintWriter(s.getOutputStream());
    String msg = in.readLine();
    System.out.println(msg);
    while(msg!="")
    {
        msg = sc.nextLine();
        out.println(msg+"\n");
        out.flush();
    }
    s.close();
    sc.close();
}
}

=============================================

package s;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TClient extends Thread
{
private int num;
private Socket s;
private BufferedReader in;
private PrintWriter out;

public Socket getS() 
{
    return s;
}

public BufferedReader getIn() 
{
    return in;
}

public PrintWriter getOut() 
{
    return out;
}

public TClient(Socket s,int num) throws IOException
{
    this.s = s;
    this.setNum(num);
    System.out.println("Client"+num);
    out = new PrintWriter(s.getOutputStream());
    in = new BufferedReader (new InputStreamReader(s.getInputStream()));
    out.println("Connected"+num+"\n");
    out.flush();
}

public void run()
{
    while(true)
    {

        try
        {
            String msg="";
            msg = in.readLine();
            System.out.println(msg);
            if (msg.equals(".")) break;
        }
        catch (IOException e)
        {

        }
    }
    try 
    {
        s.close();
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public int getNum() 
{
    return num;
}

public void setNum(int num) 
{
    this.num = num;
}
}

=============================================== =========

package s;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server 
{
public static void main(String[] args) 
{
    ServerSocket ss  ;
    Socket s = null ;
    int nb_clients = 0;
    String msg = "";
    TClient[] connexions =  new TClient[2];
    try
    {
        ss = new ServerSocket(9000);
        System.out.println("Server is listening in:"+ss.getLocalPort());
        boolean continu = false;
        while(!continu)
        {
            s = ss.accept();
            connexions[nb_clients] = new  TClient(s,nb_clients+1);
            connexions[nb_clients].start();
            nb_clients++;
            if (nb_clients>=2) continu=true;
        }
        System.out.println("Clients connected");
        s.close();
        ss.close();
    }
    catch(IOException e)
    {

    }
}

}

======================================== 每个终端的输出是:

Server is listening in:9000
Client1
Client2
Clients connected

并且2个客户的输出是:

Connection pending

Connected1

Connection pending

Connected2

如果我从1& 2到服务器,服务器输出将是这样的:

Server is listening in:9000

Client1

Client2

Clients connected

111111111111111111111111111111111111

=============================================== ================= 更新:

我改变了服务器中的条件 if(nb_clients> 2)continu = true; 现在我可以从两个客户那里收到,现在我必须知道如何让他们在客户之间进行沟通

2 个答案:

答案 0 :(得分:1)

两个客户的解决方案。 将消息从一个客户端发送到另一个客户端。

服务器必须编组客户端之间的消息。

public class Server
{
    static TClient[] connexions = new TClient[2];

    public static void send(int clientNum, String message) {
        TClient t = connexions[clientNum];
        if(t != null) {
            t.getOut().println(message);
            t.getOut().flush();
        }
    }

}

在TClient中添加:

public void sendMessage(String message) {
        int client = (getNum()-1)==1 ? 0:1;
        Server.send(client, message);
        System.out.printf("Sending message(%s) to client:%d from client:%d%n",message,client,getNum());
}

我在你的while循环中添加了一个调用。

在客户端中,我使用另一个线程从服务器接收名为ReceiveMessageThread的消息:

public class Client
{
    public static void main(String[] args) throws IOException, Throwable
   {

        Socket s;
        BufferedReader in;
        PrintWriter out;
        Scanner sc = new Scanner(System.in);
        s = new Socket(InetAddress.getLocalHost(), 9000);
        System.out.println("Connection pending");
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(s.getOutputStream());

        ReceiveMessageThread thread = new ReceiveMessageThread(in);
        String msg = in.readLine();
        System.out.println(msg);

        thread.start();
        while (msg != "")
        {
            msg = sc.nextLine();
            out.println(msg + "\n");
            out.flush();

        }
        s.close();
        sc.close();
    }

    public static class ReceiveMessageThread extends Thread
    {
        private BufferedReader in;

        public ReceiveMessageThread(BufferedReader in)
        {
            this.in = in;
        }

        public void run()
        {
            while (true)
            {
                try
                {
                    String message = readMessage(in);
                    if (message != null && !message.equals(""))
                    System.out.println(message);
                } catch (IOException ie)
                {
                    ie.printStackTrace();
                }
            }
        }

        public String readMessage(BufferedReader in) throws IOException
        {
            String msgreceived = "";
            String readValue = "";
            while (in.ready())
            {
                readValue = in.readLine();
                if (readValue != null)
                    msgreceived += readValue;
            }
            return msgreceived;
        }
    }


}

答案 1 :(得分:0)

服务器中的

改变了:

if (nb_clients>2) continu=true;

,服务器从不同的客户端读取。