在JAVA中建立客户端服务器通信?

时间:2015-04-14 07:18:12

标签: java sockets

我想在客户端和服务器之间进行双向通信,到目前为止我已经实现了单向通信。 我在JAVA中的代码看起来像,

服务器侧

    public class server{
        @SuppressWarnings("deprecation")
        public static void main(String[] args)
        {
            try{
            ServerSocket s=new ServerSocket(9998);
            Socket ss=s.accept();
            DataInputStream din=new DataInputStream(ss.getInputStream());
            DataInputStream uip=new DataInputStream(System.in);
            DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
            System.out.println("Enter message to send to client\n");
            String stc=uip.readLine();
            dout.writeBytes(""+stc);
            din.close();
            dout.close();
            uip.close();    
        }
            catch(Exception e)
            {
                System.out.println(e);
            }`enter code here`
    }
    }

客户机侧

   public class client{
    public static void main(String[] args)
    {
        try{
        Socket ss=new Socket("localhost",9998);
        DataInputStream din=new DataInputStream(ss.getInputStream());
        DataInputStream uip=new DataInputStream(System.in);
        DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
        String msg=din.readLine();
        System.out.println("Received msg is "+msg);

        din.close();
        dout.close();
        uip.close();


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

我试图在客户端获取输入并尝试以相同的方式发送到服务器。但那不起作用。我哪里错了?我该如何实现双向沟通。

在客户端,我收到了来自用户的输入并使用了.writeBytes(value);并在服务器端的din中执行了readLine(),就像我在上面的单向通信中所做的那样。但这并不奏效。我在哪里做错了?

3 个答案:

答案 0 :(得分:0)

我假设您在不同的进程中运行这两个程序,并且您只期望从服务器发送的客户端上的结果。从客户端,您不会向服务器发送任何内容。

如果您没有收到任何错误,请尝试刷新流,如:

dout.writeBytes(""+stc);
dout.flush();

来自评论:添加了以下代码。

在服务器端接收代码

// this is your code on server
dout.writeBytes(""+stc);
//Add this code 
String msgServer = din.readLine();
System.out.println("Received msg on Server: " + msgServer );

添加客户端代码:

// this is your code on client
System.out.println("Received msg is "+msg);
dout.writeBytes("Test data from client");
dout.flush();

答案 1 :(得分:0)

创建双重通信系统的最佳方法是创建两个线程,一个用于编写消息,另一个用于接收消息(在客户端和服务器端)。

侦听线程接收消息唤醒并执行某些操作。如果需要响应,则创建响应并将其添加到队列中。

写入线程定期检查要发送的消息队列。如果它有发送它们。

答案 2 :(得分:0)

这是双向客户端服务器通信的最佳方式。" dout.shutdownOutput();"在客户端发送函数后对此行进行编码。这是名为半套接字的函数,它将有助于来回通信。

相关问题