我正在开发我的第一个Java / Android套接字应用程序,它将充当发送/接收套接字客户端。我有一个现有的应用程序(服务器)通过套接字使用xml进行通信。此服务器可以随时向连接的客户端发送信息,因此我必须在创建套件后无限期地保持套接字打开。以下代码似乎部分正确,因为我可以发送和接收直接回复,但是,我无法收到未经请求的消息?
public void Connect(String ip, int port)
{
try
{
InetAddress inetAddress = InetAddress.getByName(ip);
Socket socket = new Socket(inetAddress, port);
mConnected = true;
try
{
mOutputStream = socket.getOutputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
new Thread(new NetworkConnectHandler()).start();
while (socket.isConnected())
{
while ((bytesRead = inputStream.read(buffer)) != -1)
{
mReceivedPacket = null;
byteArrayOutputStream.write(buffer, 0, bytesRead);
mReceivedPacket = byteArrayOutputStream.toString("UTF-8");
if (mReceivedPacket.indexOf(STX) > -1 && mReceivedPacket.indexOf(ETX) > -1)
{
break;
}
}
byteArrayOutputStream.reset();
if (mReceivedPacket != null)
{
IncomingPacketHandler(XmlFromString(CleanIncomingPacket(mReceivedPacket)));
}
}
}
catch (Exception ex)
{
Log.e("Network Connect", "S: Error", ex);
}
}
catch (Exception ex)
{
Log.e("Network Connect", "C: Error", ex);
}
}
public class NetworkConnectHandler implements Runnable
{
@Override
public void run() {
ConnectHandler();
}
}
protected void ConnectHandler()
{
Log.e("ConnectHandler", "Connected");
SendDoc(CreateIDPacket());
}
SendDoc在Connect方法中创建的同一套接字上向服务器发送初始消息。所有已发送的消息都将从服务器收到响应。在这种情况下,将发送消息并接收响应。