gpt4 book ai didi

c# - 第一次机会异常(exception)

转载 作者:可可西里 更新时间:2023-11-01 07:55:32 25 4
gpt4 key购买 nike

我当时正在研究 C# 中的套接字,在编写了基本的两人聊天代码后,我决定转向多人聊天,它有一个服务器和 X 个客户端。

现在,即使只有一个客户端连接,也会出现问题。一旦客户端连接,服务器和客户端都会收到一条消息,“另一个客户端已连接”或“已连接到服务器”。第二次他们都点击了确定,客户端的程序崩溃了,然后是服务器程序(我稍后会处理断开连接,我想先让它工作)。正如您从标题中猜到的那样,我得到的唯一结果是“第一次机会异常(exception)”,即使在谷歌搜索或阅读此处后,我也无法阻止它出现,也无法理解它为什么会出现。

这是调试器输出的两行:

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

The program '[6808] Chat - sockets.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

try catch 此异常时,Try-catch 不起作用。正如我之前所说,程序即使在 Debug模式下也会崩溃,没有显示任何错误。

代码如下:

客户端连接回调:

private void ClientConnectCallback(IAsyncResult res)
{
serverSocket.EndConnect(res);
MessageBox.Show("Server connected.");
serverSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ClientRecieveCallback), null);
}

buffer 是一个局部变量,一个大小为 1000 的字节数组。serverSocket 是一个套接字,我们在其上使用“BeginConnect”方法。

这是服务器接受客户端回调:

private void ServerAcceptCallback(IAsyncResult res)
{
//Recieving the socket.
Socket tempSocket = localHost.EndAccept(res);

//Creating a new buffer for it.
byte[] tempBuffer = new byte[1000];

//Adding the socket to the array.
Socket[] tempArray = clients;
clients = new Socket[tempArray.Length + 1];
Array.Copy(tempArray, clients, tempArray.Length);
clients[clients.Length - 1] = tempSocket;

//Adding the buffer to the list.
buffers.Add(tempBuffer);
MessageBox.Show("Another client connected");

//Begin receive data.
tempSocket.BeginReceive(tempBuffer, 0, tempBuffer.Length, SocketFlags.None, new AsyncCallback(ServerRecieveCallback), null);
localHost.BeginAccept(new AsyncCallback(ServerAcceptCallback), null);
numOfPpl++;
ServerSend("~~~NumOfPpl:" + numOfPpl);
}

localHost 是我们绑定(bind)到端口和任何地址的套接字,然后我们将其称为“Listen(0)”。 tempBuffer 是一个新的字节数组,我们创建它仅用作此连接的缓冲区。 clients 是一个套接字数组,包含服务器的客户端。 buffers 是客户端缓冲区的列表。

numOfPpl 是当前 session 中的人数,通过使用文本“~~~NumOfPpl:”调用 ServerSend,客户端接收下一个数字作为人数而不是消息,并分别在他们的电脑。

我希望我说清楚了,这是我在这个网站上的第一个问题。

实际上,即使是一条可以帮助我更进一步的信息(因为我现在没有什么可尝试的)也会有很大帮助。

最佳答案

您可能在套接字内遇到异常 I/O回调,它不在您的 catch block 中。

在 Visual Studio 中,单击“调试”、“异常”,然后选中所有复选框,以告诉 Visual Studio 在抛出任何异常时立即进入调试器。

关于c# - 第一次机会异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6349142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com