服务端采用JAVA编写,客户端是C,都是运行在同一台机器上,OS是LINUX
如果客户端第一次发送的数据很大,那么就会出现connection reset这个异常
可是如果第一次发送比较少,那么不会出现这个异常一旦出现这个异常,那么客户端再次发送的数据,就不能接收到了服务端:
我启动了两个线程,
一个是专门用于监听接收客户端的数据,
另外一个是专门用于处理接收到的数据,监听接收到的数据的线程代码如下:
public class ThreadRcvMsg
{
public static boolean bExitThread = false; // 退出线程标志 static ServerSocket servsock;
public static final int QUIT_SLEEP_TIME = 5000; public ThreadRcvMsg()
{
try
{
servsock = new ServerSocket(GlobalData.serviceAlarmPort);
/*设置端口重用,当上次绑定失败后,下次绑定仍能成功*/
servsock.setReuseAddress(true);
}
catch (IOException e)
{
WebuiLog.writeDebugLog("Can not create ServerSocket:"
+ e.toString());
return;
}
// 创建线程,并启动它们
new Handler(servsock).start();
}
public static CommonResult quitThreadRcvMsg()
{
bExitThread = true; //退出标记为TRUE
// 发送消息给自己,退出告警接收线程
String exitMsg = "Begin to exit.";
byte[] data = exitMsg.getBytes();
SocketClient socket = null;
socket = new SocketClient(GlobalData.localInnerIpAddr,
GlobalData.serviceAlarmPort);
if (null == socket)
{
WebuiLog.writeDebugLog("Send exit message error");
return null;
}
// send msg
CommonResult sendResult = socket.sendNotRev(data);
try
{
Thread.sleep(QUIT_SLEEP_TIME);
}
catch (Exception e)
{
WebuiLog.writeDebugLog("Sleep error:"
+ e.getLocalizedMessage());
}
return sendResult;
}
}
class Handler extends Thread
{
final static int RCV_LEN = 284; // 每次接受数据的长度7个int ServerSocket servsock;
Handler(ServerSocket socket)
{
super();
servsock = socket;
} MgmtMsg dataFlowIntoMsg(byte[] into)
{
return new MgmtMsg(into);
} public void run()
{
int j = 0;
byte[] data = new byte[RCV_LEN];
// 等待一个连接
while (true)
{
Socket clientsocket = null;
try
{
if (ThreadRcvMsg.bExitThread)
{
if (!servsock.isClosed())
{
servsock.close();
}
WebuiLog.writeDebugLog("Alarm thread exit in loop.");
break; // 退出线程
}
// 等待下一个连接
if (servsock.isClosed())
{
break;
}
//clientsocket.setReuseAddress(true);
clientsocket = servsock.accept();
BufferedInputStream in = new BufferedInputStream(clientsocket
.getInputStream());
while(in.read(data) > 0)
{
// //收到退出消息
if (true == ThreadRcvMsg.bExitThread)
{
if (null != servsock)
{
servsock.close();
}
break;
}
synchronized (GlobalData.alarmMgmtMutex)
{
GlobalData.alarmList.add(this.dataFlowIntoMsg(data));
j++;
WebuiLog.writeDebugLog("send alarm j is : " + j);
}
}
}
catch (IOException all)
{
WebuiLog.writeDebugLog("Thread handle error:"
+ all.toString());
}
finally
{
try
{
clientsocket.close();
}
catch(IOException e)
{
WebuiLog.writeDebugLog("Close alarm socket error:" + e.toString());
}
}
}
}
}碅
我在那里回答了