我正在做一个应用程序,它要求我作为客户端连接到服务器并从服务器接收数据。断开连接时,我需要重新连接。以下是我的代码:
public enum MySocketState
{
Disconnected = 0,
Connecting,
Connected
}
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[128];
void DataProcess()
{
try
{
if (_serverSocket == null || sockState == MySocketState.Disconnected)
{
Console.WriteLine("Trying to connect...");
SetupServer();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void SetupServer()
{
try
{
_serverSocket.Connect("192.168.1.11", 1000);
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
sockState = MySocketState.Connected;
Console.WriteLine("Server connected...");
_serverSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
if (_serverSocket == null)
_serverSocket = (Socket)AR.AsyncState;
int recieved = _serverSocket.EndReceive(AR);
if (recieved <= 0)
{
CloseSocket();
return;
}
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);
string strData = ASCIIEncoding.ASCII.GetString(recData);
Console.WriteLine(strData);
//Process the data stored in recData
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
CloseSocket();
}
finally
{
try
{
//Start receiving again
if (_serverSocket != null)
_serverSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex2)
{ }
}
}
public void CloseSocket()
{
try
{
if (_serverSocket != null)
{
if (_serverSocket.Connected)
_serverSocket.Shutdown(SocketShutdown.Both);
_serverSocket.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
_serverSocket = null;
sockState = MySocketState.Disconnected;
}
private void timer1_Tick(object sender, EventArgs e)
{
DataProcess();
}
我使用计时器(timer1_tick)始终检测服务器是否已连接。
但是在与服务器断开连接之后,它无法重新连接,而下面是_serverSocket.Connect("192.168.1.11", 1000)
行上的错误消息:
A first chance exception of type 'System.NullReferenceException' occurred in fform.exe
System.NullReferenceException: Object reference not set to an instance of an object.
at fform.Form1.SetupServer() in c:\Work\Project 2015\Form1.cs:line 143
at fform.Form1.DataProcess() in c:\Work\Project 2015\Form1.cs:line 79
你们知道为什么它不能连接回来?
答案 0 :(得分:0)
可能是因为你在CloseSocket()之后将_serverSocket设置为null,并且当你尝试重新连接时没有创建一个新的Socket实例。
public void CloseSocket()
{
...
_serverSocket = null;
...
}
查看错误消息中的行号
在c:\ Work \ Project 2015 \ Form1.cs中的fform.Form1.SetupServer():行 143 在c:\ Work \ Project中的fform.Form1.DataProcess() 2015 \ Form1.cs:第79行
重新连接时,您应该执行以下操作:
private void SetupServer()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Added
_serverSocket.Connect("192.168.1.11", 1000);
}
...
}