与C ++ Server连接时C#客户端暂停,但与C#Server连接时工作正常

时间:2019-03-09 11:52:26

标签: c# c++ winsock

我有C#客户端程序和C#服务器程序,它们彼此成功连接并且可以正常工作。但是,当我想将C#客户端与C ++服务器连接时,C#客户端会暂停,而C ++ Server会生成“ winsock初始化成功”和“创建套接字成功”的成功消息。

C ++服务器代码

WSADATA wsaData;

struct sockaddr_in address_of_server;
struct sockaddr_in address_of_client;

int socket_of_client;
int size_of_address_of_client = sizeof(address_of_client);

if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0) {
    printf("winsock initialization success\n");
}
else {
    printf("winsock initialization failure\n");
}

SOCKET socket_of_server = socket(AF_INET, SOCK_STREAM, 0);

if (socket_of_server == -1) {
    printf("creating socket failure\n");
}
else {
    printf("creating socket success\n");
}

memset(&address_of_server, 0, sizeof(address_of_server));
address_of_server.sin_family = AF_INET;
//address_of_server.sin_family = PF_INET;
address_of_server.sin_addr.s_addr = htonl(INADDR_ANY);
address_of_server.sin_port = htons(8888);

bind(socket_of_server, (struct sockaddr*)&address_of_server, sizeof(address_of_server));

listen(socket_of_server, 5);

ClientSocket = accept(socket_of_server, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
    printf("accept failed with error: %d\n", WSAGetLastError());
    closesocket(socket_of_server);
    WSACleanup();
    return 1;
}

socket_of_client = accept(socket_of_server, (struct sockaddr*)&address_of_client, &size_of_address_of_client);

WSACleanup();

C#客户代码

public CCRMain()
{
    InitializeComponent();
    clientSocket.Connect("127.0.0.1", 8888);    
}
void Data()
{
    MainWindow mw = (MainWindow)Application.Current.MainWindow;
    NetworkStream serverStream = mw.clientSocket.GetStream();
    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(A1G1.Text + "$");
    serverStream.Write(outStream, 0, outStream.Length);
    serverStream.Flush();

    byte[] inStream = new byte[10025];
    serverStream.Read(inStream, 0, (int)mw.clientSocket.ReceiveBufferSize);

    System.IO.MemoryStream ms = new System.IO.MemoryStream(inStream);
    System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
    int[] inComingData = new int[5];

    for (int i = 0; i < 5; i++)
    {
        inComingData[i] = br.ReadInt32();
        Debug.WriteLine(inComingData[i].ToString());
        A1G1Text.Text = inComingData[0].ToString();
    }
}   

1 个答案:

答案 0 :(得分:0)

NetworkStream.Read()被阻止。因此,只要服务器不关闭连接,该连接就不会返回,直到已读取10025字节为止。

您应该直接从网络流中读取内容,而不要复制两次(在您的情况下甚至是四次:从网络到inStream,然后到MemoryStream,再到inCommingData,再到文本变量)。

使用NetworkStream.ReadTimeout属性表示您希望Read()返回,即使不是在一段时间内归档了整个缓冲区。