c#中使用TCP socket通信,第一次打开TCP连接成功,关闭后,再次打开就失败。
privatevoidtcpStart_Click(objectsender,EventArgse)//打开TCP连接{//IPAddressipAddr=IPAddre...
private void tcpStart_Click(object sender, EventArgs e) //打开TCP连接
{
//IPAddress ipAddr = IPAddress.Parse("172.24.54.19");
IPAddress ipAddr = IPAddress.Parse(IP);
IPEndPoint ipEnd = new IPEndPoint(ipAddr, 9603);
//创建socket实例
try
{
socket.Connect(ipEnd);
btnStart.Enabled = true;
MessageBox.Show("TCP连接成功!!");
}
catch
{
MessageBox.Show("TCP连接失败!!");
}
}
private void tcpStop_Click(object sender, EventArgs e) //关闭TCP连接
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
//socket.Disconnect(true);
btnStart.Enabled = false;
btnStop.Enabled = false;
MessageBox.Show("Socket连接关闭!!");
}
catch
{
MessageBox.Show("Socket连接关闭异常!!");
}
}
这是我写的打开和关闭TCP连接的代码,各位大神们帮忙看看是哪里出了问题,需要怎么修改?谢谢!!! 展开
{
//IPAddress ipAddr = IPAddress.Parse("172.24.54.19");
IPAddress ipAddr = IPAddress.Parse(IP);
IPEndPoint ipEnd = new IPEndPoint(ipAddr, 9603);
//创建socket实例
try
{
socket.Connect(ipEnd);
btnStart.Enabled = true;
MessageBox.Show("TCP连接成功!!");
}
catch
{
MessageBox.Show("TCP连接失败!!");
}
}
private void tcpStop_Click(object sender, EventArgs e) //关闭TCP连接
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
//socket.Disconnect(true);
btnStart.Enabled = false;
btnStop.Enabled = false;
MessageBox.Show("Socket连接关闭!!");
}
catch
{
MessageBox.Show("Socket连接关闭异常!!");
}
}
这是我写的打开和关闭TCP连接的代码,各位大神们帮忙看看是哪里出了问题,需要怎么修改?谢谢!!! 展开
1个回答
展开全部
关闭socket.Close()后,socket对象就为null,再次打开socket时会发生异常。稍微修改一下:
private void tcpStart_Click(object sender, EventArgs e)
{
//IPAddress ipAddr = IPAddress.Parse("172.24.54.19");
IPAddress ipAddr = IPAddress.Parse(IP);
IPEndPoint ipEnd = new IPEndPoint(ipAddr, 9603);
//创建socket实例!加上这句!!!!!
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp)
try
{
socket.Connect(ipEnd);
btnStart.Enabled = true;
MessageBox.Show("TCP连接成功!!");
}
catch
{
MessageBox.Show("TCP连接失败!!");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询