[英]Establishing a client server Communication in JAVA?
我想在客户端和服务器之间执行双向通信,到目前为止,我已经实现了双向通信。 我在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()
,就像我上面以一种方式进行的通信一样。 但这是行不通的。 我在哪里做错了?
我假设您正在不同的进程中运行两个程序,并且只期望从服务器发送的客户端上有结果。 从客户端,您没有向服务器发送任何内容。
如果没有出现任何错误,请尝试刷新流,例如:
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();
创建双重通信系统的最佳方法是创建两个线程(一个用于写消息,另一个用于接收消息)(在客户端和服务器端)。
侦听线程会自己接收一条消息,然后执行某些操作。 如果需要响应,则创建响应并将其添加到队列中。
编写线程定期检查要发送的消息队列。 如果有,则将其发送。
这是双向客户端服务器通信的最佳方法。“ dout.shutdownOutput();” 在客户端的send函数之后编写此行代码。此函数名为半套接字关闭,将有助于来回通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.