Reputation: 65
I make a java socket server and c socket client, here are the code
Java Socket Server:
int Send_Request(String s) {
try {
os = socket.getOutputStream();
os.write(s.getBytes());
os.flush();
Log.d(tag,"Data = " + s);
return 0;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(tag,"Send Request Error");
return -1;
}
C socket client:
void* recv_request()
{
int i,in;
char buf[1024];
while(1)
{
if ( ( in = read(sockfd, buf, strlen(buf)) ) != -1 )
{
LOGD("Received = %s ...",buf);
sendServerCutText(buf);
memset(buf,0,strlen(buf));
}
}
}
The problem is .. when i send from the server, it is blocking on flush(), the c client cannot receive until there is another Send_Request called.
where is the problem??
Upvotes: 2
Views: 3979
Reputation: 96258
There is a conceptual problem. You think TCP is message oriented (sending messages with specified length). It's not like that, it is only providing a stream of bytes.
For sending a message with a specified length a common technique is to send first the length (encoded in fixed length, eg 4 byte integer in network byte order) and then the actual message.
There's also an implementation problem, the 3rd argument for read should be the maximum read length, which should be 1024, executing strlen
on a non-initialized local char array is clearly undefined-behaviour.
Upvotes: 3