java.net.SocketException:软件导致连接中止:套接字写入错误
问题描述:
我试图从Java桌面应用程序向J2ME应用程序发送图像。问题是,我得到这个异常:java.net.SocketException:软件导致连接中止:套接字写入错误
java.net.SocketException: Software caused connection abort: socket write error
我已经看了看周围上了网,虽然这个问题并不罕见,我无法找到一个具体的解决方案。在传输图像之前,我将图像转换为字节数组。这些都是在桌面应用程序,并在J2ME分别
public void send(String ID, byte[] serverMessage) throws Exception
{
//Get the IP and Port of the person to which the message is to be sent.
String[] connectionDetails = this.userDetails.get(ID).split(",");
Socket sock = new Socket(InetAddress.getByName(connectionDetails[0]), Integer.parseInt(connectionDetails[1]));
OutputStream os = sock.getOutputStream();
for (int i = 0; i < serverMessage.length; i++)
{
os.write((int) serverMessage[i]);
}
os.flush();
os.close();
sock.close();
}
private void read(final StreamConnection slaveSock)
{
Runnable runnable = new Runnable()
{
public void run()
{
try
{
DataInputStream dataInputStream = slaveSock.openDataInputStream();
int inputChar;
StringBuffer results = new StringBuffer();
while ((inputChar = dataInputStream.read()) != -1)
{
results.append((char) inputChar);
}
dataInputStream.close();
slaveSock.close();
parseMessage(results.toString());
results = null;
}
catch(Exception e)
{
e.printStackTrace();
Alert alertMsg = new Alert("Error", "An error has occured while reading a message from the server:\n" + e.getMessage(), null, AlertType.ERROR);
alertMsg.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alertMsg, resultScreen);
}
}
};
new Thread(runnable).start();
}
我在局域网发送消息找到了方法,我没有问题,当我发的不是图片简短的文本信息。另外,我使用wireshark,似乎桌面应用程序只发送部分消息。任何帮助将不胜感激。此外,一切工作在J2ME模拟器上。
答
请参考答案Official reasons for "Software caused connection abort: socket write error"
编辑
,我不认为还有更多的是一般可以说了,似乎没有要什么异常有关代码会导致连接中止。然而,我会注意到:
- 将字节转换为
write
调用的整数是不必要的。它会自动升级。 - 使用
write(byte[])
而不是write(int)
会更好(更简单,可能在网络流量方面更高效)。 - 接收端假定每个字节表示一个完整的字符。这可能是不正确的,这取决于发送方如何形成要传输的字节,并且
- 通过发送字节计数开始是一个好主意,以便接收方能够判断发送方发送之前是否有问题整个字节数组。
我已经经历了这些答案。我查看了Windows事件日志,但没有看到任何相关的事件,尽管我没有经历过这些日志的经验。其次,我也尝试在shutdownOutput()中添加;但仍然无济于事。 最后,我从J2ME应用程序中得到一个错误,说该套接字已关闭。 – npinti 2010-05-18 23:08:19
呃...我不知道如何,但我似乎现在可以得到它的工作。我尝试将转换替换为整数部分,但是这完全打乱了我的应用程序,完全禁用它。我试着今天发送它,它工作。我的猜测是,这是一些外部原因,可能是路由器重新启动或其他。 – npinti 2010-05-19 08:17:11