如何使用套接字从服务器发送和接收消息? [英] How to use socket to send and receive message from server?
问题描述
大家好,我有一个任务,我想向服务器发送消息,然后得到回复.我不断收到 failed 1recvfrom failed: EBADF (Bad file descriptor)
错误,我是这个套接字的新手.希望有人可以帮助我.这是我的异步任务:
Hi guys so I have a task where I'm suppose to send a message to a server, and then get a reply back. I keep getting failed 1recvfrom failed: EBADF (Bad file descriptor)
error and I'm new to this socket stuff. Hopefully someone can help me out. Here's my async task:
private class SendDataAsyncTask extends AsyncTask<Void,Void,Void>
{
private String reply = "";
@Override
protected Void doInBackground(Void... params)
{
try {
Socket socket = new Socket("ip",portNumber);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
//printWriter.write("hello there");
printWriter.println("hello there");
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter.flush();
reply = bufferedReader.readLine();
if(reply != null && !reply.equals(""))
{
Log.d(SOCKET_TESTING_TAG,"my message is " + reply);
}
else
{
Log.d(SOCKET_TESTING_TAG,"no message yet");
}
Log.d(SOCKET_TESTING_TAG,"break 3");
printWriter.close();
}
catch (IOException e)
{
Log.d(SOCKET_TESTING_TAG,"failed " + e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
public void onPostExecute(Void var)
{
tv_response.setText(reply);
}
}
- 注意:当我在
printWriter.flush()
之前放置 if 语句来检查空读取行时,我仍然收到错误. - Note: When I put the if statement to check for the null readline before
printWriter.flush()
I still get an error.
推荐答案
printWriter.close();
关闭套接字的输入或输出流会关闭另一个流和套接字.删除这两个事件.
Closing the input or output stream of a socket closes the other stream and the socket. Remove both occurrences.
if(bufferedReader.readLine() != null)
这没有意义.如果它不为空,您将丢弃该行,然后阅读下一行.您需要将结果存储到一个变量中.
This doesn't make sense. You are throwing the line away and then reading the next line if it wasn't null. You need to store the result into a variable.
您可能需要使用 printWriter.println()
而不是 printWriter.write()
.可能对方也在读行,而你没有发送(没有行终止符).
You probably need to use printWriter.println()
instead of printWriter.write()
. Probably the peer is reading lines too, and you aren't sending one (no line terminator).
如果 reply == null
表示对方已经关闭了连接.不是还没有消息".空字符串可能是协议错误,但也不是尚无消息".
If reply == null
it means the peer has closed the connection. Not 'no message yet'. An empty string may be a protocol error but it also is not 'no message yet'.
这篇关于如何使用套接字从服务器发送和接收消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!