C#客户端到C ++服务器Tcp套接字连接错误

时间:2017-11-08 03:41:31

标签: c# c++ sockets server client

客户端是跨平台应用程序(android& ios)(C#) 服务器是Windows。(C ++)

我成功连接到服务器,但此服务器recv函数严重返回0。但是当我尝试使用c ++客户端连接服务器时,我不会遇到这个问题。

当客户端关闭Recv函数返回0时,我不想这样做"继续;"如果recv返回0。

我将此客户端代码添加到Button。单击按钮后套接字是否关闭?

客户C#代码:

private static async void ConnectAsTcpClient()
    {

            using (var tcpClient = new TcpClient())
            {
                //Console.WriteLine("[Client] Connecting to server");
                await tcpClient.ConnectAsync("127.0.0.1", 12312);
                Console.WriteLine("[Client] Connected to server");
            }

    }

服务器C ++代码: SOCKET袜子;

// for our thread
DWORD thread;

WSADATA wsaData;
sockaddr_in server;

// start winsock
int ret = WSAStartup(0x101, &wsaData); // use highest version of winsock avalible

if (ret != 0)
{
    return 0;
}

// fill in winsock struct ... 
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(12312); // listen on telnet port 23

                              // create our socket
sock = socket(AF_INET, SOCK_STREAM, 0);

if (sock == INVALID_SOCKET)
{
    return 0;
}

// bind our socket to a port(port 123) 
if (bind(sock, (sockaddr*)&server, sizeof(server)) != 0)
{
    return 0;
}

// listen for a connection  
if (listen(sock, 5) != 0)
{
    return 0;
}

// socket that we snedzrecv data on
SOCKET client;

sockaddr_in from;
int fromlen = sizeof(from);
printf("Server Started\n");
client = accept(sock, (struct sockaddr*)&from, &fromlen);
printf("Client connected\r\n");

while (true)
{
    res = recv(current_client, buf, sizeof(buf), 0); // recv cmds


    // multi Thread
    Sleep(30);

    if (res == 0 || res >= 150)
    {
        printf("Recv Failed! = %d\n", res);
        continue;
    }

1 个答案:

答案 0 :(得分:0)

客户端不会写任何内容,而是让tcpClient对象超出范围,从而断开连接,导致recv在服务器中返回0

顺便说一下,您忘记检查recv来电时的实际错误(res == SOCKET_ERROR时)。