有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java c#socket client multiple BeginSend()未到达服务器

我正在为客户端使用unity引擎。我测试了以下代码[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)只获取一个数据(bytebuffer),而不是四个。所以我尝试了使用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());
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

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