我使用套接字用java编写了一个简单的客户端服务器程序。当我在一台机器上运行 ServerClas.java 并在另一台机器上运行 Clientclas.java 时,看起来套接字已连接,但数据未传输。我可以看出它们已连接,因为当 Server.java 在服务器计算机中终止时,客户端会捕获异常,表示连接已重置。我无法弄清楚为什么数据没有被传输。 请纠正我的错误。
机器使用 netgear 路由器连接。 java运行环境为javase1.6
Clientclas.java是
public static void main(String arg[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter your name:");
name=s.nextLine();
try {
InetAddress add = InetAddress.getByName("10.0.0.9");
Socket sock = new Socket(add,7777);
OutputStream os = sock.getOutputStream();
Writer out = new OutputStreamWriter(os);
out.write("Hai ..!! This is "+name+". Im connected to you");
InputStream is = sock.getInputStream();
is = new BufferedInputStream(is);
int i;
while((i=is.read())!=-1)
{
System.out.write(i);
}
sock.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Cannot connect to host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ServerClas.java 是
public static void main(String arg[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter your name:");
name = s.nextLine();
ServerSocket sock;
try{
System.out.println("terminating...");
sock = new ServerSocket(7777);
System.out.println("Your prog is listening to clients on port 7777 on"+sock.getInetAddress());
Socket soc = sock.accept();
InputStream is = soc.getInputStream();
is = new BufferedInputStream(is);
int i;
while((i=is.read())!=-1)
{
System.out.write(i);
}
System.out.println("Data recieved");
OutputStream os = soc.getOutputStream();
Writer out = new OutputStreamWriter(os);
out.write("Hai ..!! This is "+ServerClas.name+". Im connected to you");
out.flush(); }
catch(IOException e)
{
System.out.println("Excption caught");
e.printStackTrace();
}
s.close();
}
最佳答案
当您从输入流读取数据时,您会一直读取直到关闭,但直到收到回复后才会关闭连接,而只有关闭连接才能收到回复。
即你陷入了僵局。
您需要某种方式知道消息何时发送,同时连接仍处于打开状态,以便您可以发送回复。我建议在行尾发送 \n
并在看到此内容时停止阅读。
关于java - java套接字连接中客户端和服务器之间数据传输不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21535489/