【发布时间】: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