简体   繁体   English

Socket C客户端和Java服务器只能发送一个String

[英]Socket C client and Java server can send only one String

My Java server sends an Integer and a String (to a C client): 我的Java服务器发送一个Integer和一个String(到一个C客户端):

   DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

   dos.writeInt(ClientNumber); //send the Integer

   String randomString= getRandomValue(10,20);
   dos.writeUTF(randomString);  //send the String
   String clientString=din.readLine();

The C code for the client that's reading them is: 正在阅读它们的客户端的C代码是:

if( recv( to_server_socket, &reply, sizeof( reply ), MSG_WAITALL ) != sizeof( reply ) )
    {
        printf( "socket read failed");
        exit( -1 );
    }
char buf[50];
int byte_count;
byte_count = recv(to_server_socket, buf, sizeof buf, 0);
printf("recv()'d %d bytes of data in buf\n", byte_count)

Until here, it works fine. 直到这里,它工作正常。

Now, I want to send another String to the Client. 现在,我想向客户端发送另一个字符串。 So, I tried just adding the line: 所以,我试着添加一行:

dos.writeUTF("blabla");

It's still working and when I tried to get the client to read it, I added: 它仍在工作,当我试图让客户端阅读它时,我补充道:

byte_count2 = recv(to_server_socket, buf2, sizeof buf2, 0);
   printf("recv()'d %d bytes of data in buf\n", byte_count2);

And it doesn't work. 它不起作用。 The client receives the number and the first String but it doesn't send anything and doesn't receive the "blabla" string. 客户端接收数字和第一个字符串,但它不发送任何内容,也不接收“blabla”字符串。 I'm not sure if the problem is in the client or the server. 我不确定问题出在客户端还是服务器上。

Can anyone explain to me what I'm doing wrong? 谁能向我解释我做错了什么?

Try closing your dos(DataOutpuStream) after every write. 每次写入后尝试关闭dos(DataOutpuStream)。 You may try to check first if flush helps. 如果冲洗有帮助,您可以先尝试检查。

You are mixing your protocols. 您正在混合您的协议。 I suggest you use either binary or text wire format. 我建议你使用二进制或文本线格式。 It's not clear which one you are trying to use. 目前尚不清楚您尝试使用哪一个。

I suggest text wire format as it is easier to work with in this case. 我建议文本线格式,因为在这种情况下更容易使用。 ie don't DataInputStream or DataOutputStream as these are for binary formats. 即不要将DataInputStream或DataOutputStream用于二进制格式。

Instead you can use BufferedReader for reading lines of text and PrintWriter for writing lines of text. 相反,您可以使用BufferedReader读取文本行,使用PrintWriter写入文本行。 You can test your server works by connecting to it with telnet ie if it doesn't work with telnet, it won't work with C. 您可以通过telnet连接到服务器来测试您的服务器,即如果它不能与telnet一起使用,它将无法与C一起使用。

Once this is working, get your C client to work as well. 一旦这样做,让你的C客户端也能正常工作。 BTW You shouldn't assume that one write translates to one read. 顺便说一句你不应该假设一次写入转换为一次读取。 You are writing a Stream of data, not messages. 您正在编写数据流,而不是消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM