【发布时间】:2015-04-21 12:11:36
【问题描述】:
我有一个“开始”和“停止”按钮。单击开始按钮时,会创建一个新套接字并建立连接。单击停止按钮时,套接字将关闭、断开连接、关闭并处理以确保它完全消失。
至少,这就是我的想法:在停止连接后单击开始时,会创建一个新的套接字等。但是一旦我发送数据,数据就会发送 x 次我创建套接字的次数(因此,x 的数量次我点击了开始按钮)。
这是开始的代码:
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Socket soc; is declared at class-level
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(IP);
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, port);
try
{
soc.Connect(remoteEP);
soc.Send(jsonSettings);
}
catch (SocketException e)
{
MessageBox.Show("Could not connect to socket");
}
这是停止代码:
if (soc != null)
{
soc.Shutdown(SocketShutdown.Both);
soc.Disconnect(false);
soc.Close();
soc.Dispose();
}
这在VSTO PowerPoint add-in 应用程序中使用,如果这可能导致任何额外的特性,当建立连接时,我将字符串数据发送到侦听此端口的 Python 服务器。每次关闭连接时,Python 服务器都会退出它的监听数据循环并返回等待连接状态(对于多个启动/停止连接)。
发送数据代码:
// this is called each time the user goes to another slide in the PowerPoint presentation
byte[] byData = System.Text.Encoding.ASCII.GetBytes(stringValue);
soc.Send(byData);
谁能指出我做错了什么,为什么即使我断开连接并关闭了套接字连接,它们仍然以某种方式继续存在和发送数据?
【问题讨论】: