c# - “Socket.Receive”函数后套接字丢失连接
问题描述
我有 ac# 客户端。客户端的任务是登录到服务器。
问题是:当我想登录时,我使用的是在“wpf”窗口初始化时创建的 TCP 套接字。使用套接字发送一次数据后,一切正常,但是当我想再次使用同一个套接字发送数据时,会弹出此异常:
System.ObjectDisposedException: '无法访问已处置的对象。对象名称:'System.Net.Sockets.Socket'。'
经过一番测试,我发现问题是由 Socket.Receive 函数引起的。我在调用函数之前检查了套接字,并且套接字已连接(Socket.Connected == true),从函数返回后,套接字未连接(Socket.Connected == false)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
// Get host related information.
IPHostEntry hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily.
foreach (IPAddress address in hostEntry.AddressList)
{
//attempting to connect.
IPEndPoint ipe = new IPEndPoint(address, port);
//making a temp socket to check the connection (if something went wronge/ the server isnt active)
Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
// attempting connection.
tempSocket.Connect(ipe);
}
catch (Exception)
{
Console.WriteLine("Request timed out");
}
//if we connected to the server, we are ok to continue.
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
//else the connection isnt successful (the server might not respond) we need to try again.
else
{
continue;
}
}
Globals.SOCKET = s;
return s;
}
//This func will send a request to the server and returns the server's response.
public static string SocketSendReceive(string server, int port, string request, Socket socket = null)
{
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
string response = "";
// Create a socket connection with the specified server and port.
if (socket == null)
socket = ConnectSocket(server, port);
using (socket)
{
// If the connection faild and couldnt maintain a socket.
if (socket.Connected == false)
return ("Connection failed");
// Send request to the server.
socket.Send(bytesSent, bytesSent.Length, 0);
// Receiving the packet from the server.
int bytes = socket.Receive(bytesReceived, bytesReceived.Length,0);//***The problem occures Here***
response = response + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
return response;
}
第二个功能是从服务器发送和接收数据的功能。第一个只是连接并创建一个套接字
谢谢你的帮助!-安东尼
解决方案
改变
socket.Receive(bytesReceived, bytesReceived.Length,0)
至
socket.Receive(bytesReceived, 0, bytesReceived.Length)
推荐阅读
- spring - 在Tomcat中部署项目时一次又一次地创建删除的列?
- python - 如何遍历嵌套的子节点
- arrays - 我想在点击反应时为数组添加值
- vba - 如何将电子邮件中的矩阵数据替换为用户表单文本框中的数据?
- highcharts - Highchart yaxis 类别拥挤
- vue.js - 我怎样才能让几个孩子动态路线?
- reactjs - 使用 rollupJs 构建 ES6 模块时 Material-UI ThemeProvider 的挂钩调用无效
- c# - 单击 ASP.NET Core 中的按钮时如何防止验证?
- javascript - 如何使用javascript es6将数组插入spanner数据库中的列
- python - 在熊猫中显示一列中的常用值一次