I am still new with sockets, and am having a little problem with creating an android client ac server.
The c server is runs well, and android client connects also well to the c server. But the problem comes when communicating with the server. When I try to send a simple message, the server doesn't seem to receive it at all.
So here is the code of the server waiting for the message :
void readMsg(int client){
char buffer[1024];
int n = 0;
memset(buffer, 0, sizeof(buffer));
printf("waiting for message..\n");
while(( n=recv(client, buffer, sizeof buffer - 1, 0)) > 0){
printf("recv=%s\n", buffer);
}
printf("n=%d\n", n);
}
And nothing at all is displayed. It's blocked on waiting for message..
.
And concerning the java code to send the message, here it is :
OutputStreamWriter osw;
PrintWriter pw;
try {
osw = new OutputStreamWriter(server.getOutputStream(), "UTF-8");
pw = new PrintWriter(osw, true);
pw.print(msg);
pw.flush();
}catch(IOException ioe) {
ioe.printStackTrace();
}
[EDIT]
Just to provide more information, the function readMsg()
is called just after starting the server and once the client is connected.
For more information, here is the way I connect to the server :
try{
//I am sure that the host and port are correct
Socket server = new Socket(host, port);
}catch(IOException ioe){
ioe.printStackTrace();
}
Okay, so I found out what went wrong, I was in fact connecting twice to the server. As a result it couldn't send the message through the right socket.
Sorry for everything and thank you for all your help
[/EDIT]
I've already tried several solutions by looking at several other posts on this site.
Thank you in advance for all help
use a println
instead of print
, also wrap the OutputStreamWriter
inside a BufferedWriter
pw = new PrintWriter(new BufferedWriter(osw), true);
pw.println(msg);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.