【问题标题】:c# socket client multiple BeginSend() don't arrive to serverc#socket客户端多个BeginSend()没有到达服务器
【发布时间】:2021-10-28 01:28:46
【问题描述】:

我正在为客户端使用统一引擎。我测试了下面的代码[method1]:

//connect to server
//unity gameobject c# client code

bool ConnectToServer() {
    try { 
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
        socket.Connect(IPAddress.Parse(serverIP), serverPort); 
        socket.Blocking = true;
        AsyncObject ao = new AsyncObject(1024); 
        ao.WorkingSocket = socket; 
        receiveHandler = new AsyncCallback(OnReceive); 
        socket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, receiveHandler, ao); 
        return true;
    } 
    catch(SocketException e) { 
        Debug.Log(e.Message); 
        return false;
    } 
}

private void update() {
    //when keyboard is pressed
    socket.send(bytebuffer);
    socket.send(bytebuffer);
    socket.send(bytebuffer);
    socket.send(bytebuffer);
}

我发现我的 java 服务器(使用 ServerSocketChannel 和 Selector)只得到一个数据(字节缓冲区)而不是四个。所以我尝试了使用 Stack[method2] 的其他代码:

Stack<byte[]> outDatas;
IAsyncResult res;
bool isSending = false;

void update() {
    if(outDatas.Count > 0 && res.IsComplete && isSending == false) {
        byte[] outData = outDatas.Pop();
        isSending = true;
        res = socket.BeginSend(outData, 0, outData.Length, 0, new AsyncCallback(onSendEnd), null);
    }
}

void onEndSend(IAsyncResult ar) {
        socket.EndSend(ar);
        isSending = false;
}

//use this function instead of socket.send
public void SendRequest(byte[] data) {
        outDatas.Push(data);
}

但是服务器只得到一个数据,而不是四个。这使我的游戏数据泄漏。为什么 [method2] 没有按我的预期工作,我怎样才能按我的预期工作?

java服务器更新代码:

public void update(int tick) {
    selector.selectNow();
    iterator = selector.selectedKeys().iterator();
    while(iterator.hasNext()) {
        SelectionKey key = iterator.next();
        iterator.remove();
        if(key.isAcceptable()) {
            SocketChannel clientSocket = ((ServerSocketChannel)key.channel()).accept();
            clientSocket.configureBlocking(false);
            clientSocket.register(selector, SelectionKey.OP_READ, user);
        }
        else if(key.isReadable()) {
            SocketChannel clientSocket = (SocketChannel)key.channel();
            inputBuffer.clear();
            int result = clientSocket.read(inputBuffer);
            handleInput((User)key.attachment());
        }
    }
}

【问题讨论】:

  • 您是否检查过网络流量以消除您发送但接收不正确的情况。 wireshark.org然后你就会知道关注点在哪里,发送者还是接收者。
  • 数据通过套接字流式传输。如果客户端快速写入 4 次,服务器可能会在一个数据包中接收所有数据。
  • @Olivier 我检查了从服务器接收到的字节长度,它是我预期的 4 倍。哇。谢谢。

标签: java c# sockets tcp client-server


【解决方案1】:

我检查了服务器中的输入字节长度,它是我预期的 4 倍。正如@Olivier 在评论中所说,服务器在一个数据包中收到数据。

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
猜你喜欢
  • 1970-01-01
  • 2014-02-19
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多