Socket 关闭时出现 错误:"由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。"

csgxiao 2008-01-03 10:38:54
代码:

public void State()
{
try
{
mythread = new Thread(new ThreadStart(BeginListen));
mythread.Start();
}
catch (Exception ex)
{
eventLog_SendWorks.WriteEntry("监听端口线程启动错误提示:" + ex.Message, EventLogEntryType.Error);
}
}
public void Close()
{
try
{
//System.Environment.Exit(System.Environment.ExitCode);

socket.Shutdown(SocketShutdown.Both);
socket.Close();
mythread.Abort();
}
catch (ObjectDisposedException ex)
{
eventLog_SendWorks.WriteEntry("ObjectDisposedException错误!:"+ex.Message,EventLogEntryType.Error);
}
catch (Exception ex)
{

eventLog_SendWorks.WriteEntry("关闭Socket和Thread是出错:" + ex.Message, EventLogEntryType.Error);
}
}




public static IPAddress GetServerIP()
{
IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName()); //获取本地主机的地址
return ieh.AddressList[0];
}
private void BeginListen()
{
IPAddress ServerIp = GetServerIP();
IPEndPoint iep = new IPEndPoint(ServerIp, 8000);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

byte[] byteMessage = new byte[1024];

socket.Bind(iep);

while (true)
{
try
{
socket.Listen(5);
Socket newSocket = socket.Accept();
newSocket.Receive(byteMessage);

newSocket.Shutdown(SocketShutdown.Both);
newSocket.Close();

string msg = Encoding.Default.GetString(byteMessage);
msg = msg.Substring(0, 13);
if (msg == "ProWorkUpdate")
{
try
{
eventLog_SendWorks.WriteEntry("数据库更新,更新数据!");
this.timer_SendMessage.Enabled = false;

if (SendTable != null)
{
SendTable.Clear();
}
dtTable = GetData(); //从数据库中读取在某一段是时间间内可能要发的事务信息
OperationDataTable(); //向发送事务表(SendTable)中添加数据

this.timer_SendMessage.Enabled = true;
}
catch (Exception ex)
{
eventLog_SendWorks.WriteEntry("触发数据更新时出错:" + ex.Message);
}
//lbl_BeginInvoke.BeginInvoke(new InvokeDelegateReadData(ReadData));
}
//Thread.Sleep(1000);
}
catch (SocketException ex)
{
//MessageBox.Show(ex.Message, "Socket错误提示!");
eventLog_SendWorks.WriteEntry("Socket连接错误提示:" + ex.Message,EventLogEntryType.Error);
}
}
}
...全文
1147 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
才才 2011-10-05
  • 打赏
  • 举报
回复
我也遇到这个问题。在找资料
hkdeaccp 2008-01-03
  • 打赏
  • 举报
回复
不懂!最近在学习socket,帮你顶下,学习了.

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧