我应该在此代码中进行哪些更改,以使此双向聊天工作

时间:2014-06-05 14:14:58

标签: java serversocket

我正在尝试制作双向聊天系统,其中两个人可以使用网络聊天。

我创建了这个服务器端,它将管理通信

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket server=new ServerSocket(2000);
        ServerSocket server2=new ServerSocket(2001);
        System.out.println("srver is ready to to recieve therequest ,");
        Socket socket=server.accept();
        Socket socket2=server2.accept();
        System.out.println("requst received,conetion completed");
        Thread.sleep(2000);
        System.out.println("wating for the client message");
        int a,b;
        OutputStream o=socket.getOutputStream();
        OutputStream o2=socket2.getOutputStream();
        InputStream i1=socket.getInputStream();
        InputStream i2=socket2.getInputStream();
        while(true)
        {
         while((a=i1.read())!=-1)
         {
             System.out.println(a);
             o2.write(a);

         }
         while((b=i2.read())!=-1)
         {
             o.write(b);
         }
        }

    }
}

现在我很困惑我将如何使客户端这样,两个用户互相交谈,任何人都可以发起谈话,并且消息将在另一端接收,即使他正在写一些东西

我试过但不成功这是代码

//

 class b {
    public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
        System.out.println("client started ,sendng connection request");
        Thread.sleep(3000);
        Socket socket =new Socket("localhost",2001);
        System.out.println("connection completed .sending message");
        BufferedReader buf=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream p=new PrintStream(socket.getOutputStream());
        Scanner s=new Scanner(System.in);
        while(true)
        {
            String ack;
            if((ack=buf.readLine())!=null)
                System.out.println(ack);
            System.out.println("enter the message to send ,out to terminate");
            String msg=s.nextLine();
            p.println(msg);
            if(msg.equalsIgnoreCase("out"))
                break;

        }
        System.out.println("closing  connection");Thread.sleep(5000);
        socket.close();
        System.out.println("conection closed");
    }

}

一个人可以建议我应该改变什么,以便我可以实现它。

0 个答案:

没有答案