【问题标题】:How to receive data from server with client on c#?如何在 C# 上使用客户端从服务器接收数据?
【发布时间】:2018-04-21 17:49:59
【问题描述】:

我正在制作一个小游戏。基于 C++ 的服务器和基于 C# 的客户端。我在接收数据时遇到问题,我不明白它是如何工作的,我需要第二个套接字来接收吗?还是第一个套接字连接并同时可用于接收?这是客户

public class Connection
{
    static private string ip = "127.0.0.1";
    static private int port = 54000;

    static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   // static Socket acpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    public static void connectToServer()
    {
        socket.Connect(ip, port);

    }

    public static void sendData(byte[] buffer)
    {
        socket.Send(buffer);
    }

    public static byte[] encodeMessage(string message)
    {
        byte[] bf = Encoding.ASCII.GetBytes(message);
        return bf;
    }

    public static void recvData()
    {
        byte[] buf = new byte[256];
        byte[] copy = new byte[256];

        try
        {
            socket.Receive(buf);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error");
        }

        if (buf != copy)
        {
            Console.WriteLine(Encoding.ASCII.GetChars(buf).ToString());

            buf = copy;
        }
    }

}

这是服务器:

int main() {

//init sock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);

int wsok = WSAStartup(ver, &wsData);
if (wsok != 0) {
    cerr << "Error while init\n";
    return 0;
}

//create
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET) {
    cerr << "Error while creating\n";
    return 0;
}

//bind
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY;

bind(listening, (sockaddr*)&hint, sizeof(hint));

//tell winsock that the socket is for listen
listen(listening, SOMAXCONN);


fd_set master;

FD_ZERO(&master);
FD_SET(listening, &master);

while (true) {
    fd_set copy = master;

    int socketCount = select(0, &copy, nullptr, nullptr, nullptr);

    for (int i = 0; i < socketCount; i++) {
        SOCKET sock = copy.fd_array[i];
        if (sock == listening) {
            //accept connection
            SOCKET client = accept(listening, nullptr, nullptr);

            //add connection to list(&master)
            FD_SET(client, &master);

            //send welcome msg to connected client
            string welcomeMsg = "Your connected!";
            send(client, welcomeMsg.c_str(), welcomeMsg.size() + 1, 0);
        }
        else{

            //accept message
            char buf[32];
            ZeroMemory(buf, 32);
            string str;
            int cnt = 0;
            int bytesIn = recv(sock, buf, 32, 0);

            for (int i = 0; i < sizeof(buf); i++) {
                if (buf[i] != '0') {
                    content[cnt] = buf[i];
                    cnt++;
                }
            }
            if (bytesIn <= 0) {
                closesocket(sock);
                FD_CLR(sock, &master);
            }
            else {
                for (int i = 0; i < sizeof(buf); i++) {
                    cout << content[i];
                }
                for (int i = 0; i < master.fd_count; i++) {
                    SOCKET outSock = master.fd_array[i];
                    if (outSock != listening && outSock != sock) {
                        send(outSock, content, cnt, 0);
                        cout << "Message Send..." << endl;
                    }
                } 
            }
        }
    }

}

我有一个计时器,我在其中调用 recvData()。问题是连接后它返回“您已连接!”但在那之后它就卡住了,不起作用。如果我评论 Socket.Receive 我没有问题,但我需要这个接收。谢谢

【问题讨论】:

    标签: c# c++ server client winsock


    【解决方案1】:

    您不必使用第二个套接字来接收数据,但SendReceive 是同步函数,因此线程被阻塞,直到当前操作完成其工作。对于接收,套接字必须至少接收一个字节才能解除对应用程序的阻塞。如果没有可用数据,Receive 将无限期等待,除非您使用 ReceiveTimeout 属性指定超时。 为避免阻塞部分,请使用异步函数BeginReceiveBeginSendMSDN 有一个使用异步套接字的完整服务器 - 客户端示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 2022-01-09
      • 1970-01-01
      • 2021-09-30
      相关资源
      最近更新 更多