Java客户端到C#服务器。没有收到负数
我有一个Java应用程序向Unity中的c#游戏发送坐标。我的数据被检出,除了负值。相反,我只得到63或250个左右。取决于编码 以下是我的Java客户端应用程序:Java客户端到C#服务器。没有收到负数,java,c#,networking,tcp,byte,Java,C#,Networking,Tcp,Byte,我有一个Java应用程序向Unity中的c#游戏发送坐标。我的数据被检出,除了负值。相反,我只得到63或250个左右。取决于编码 以下是我的Java客户端应用程序: @Override public void run() { //Keep in a loop as long as the running variable is true while(running) { //Try catch block to catch exceptions for
@Override
public void run() {
//Keep in a loop as long as the running variable is true
while(running)
{
//Try catch block to catch exceptions for the networking code
try{
data1[0]=currentPlayer; // These are integers
.....
data1[8]=sendPause;
for(int i=0; i<=9;i++){
buf1[i]=(byte)data1[i]; //Casting to byte array
//System.out.println(buf1[i]);
}
//socket is created in "onCreate" earlier
socket.setTcpNoDelay(true);
out = socket.getOutputStream();
dos = new DataOutputStream(out);
dos.write(buf1, 0, buf1.length);
dos.flush();
synchronized(this){ this.wait(30); } //This is to minimize the frequency
}catch(Exception e)
{
Log.e("TCP", "Error",e);
}
}
}
@覆盖
公开募捐{
//只要运行变量为true,就保持在循环中
(跑步时)
{
//尝试捕获块来捕获网络代码的异常
试一试{
data1[0]=currentPlayer;//这些是整数
.....
数据1[8]=发送暂停;
对于(int i=0;i我认为您的问题是在C#代码中使用字节数组。java中的字节范围为-128到127。C#中的字节范围为0到255。请尝试将收到的字节数组复制到sbyte数组中:
sbyte[] signedB = new sbyte[bytes.Length];
Buffer.BlockCopy(bytes, 0, signedB, 0, bytes.Length);
在此之后检查signedB的值。您真的需要在C端使用编码吗。您在消息中使用了字符串吗?您收到的数据已经是字节了。
。您第一次将其转换为字符串(丢失一些信息)然后将其转换回字节数组。毫无意义…是的,谢谢你指出这一点。我尝试了很多东西,但这只会阻碍我。谢谢你,伙计们,我尝试过这个,但在这种情况下,我不能使用stream.Read函数,因为它只需要字节,而不需要sbyte。“System.IO.stream.Read(byte[],int,int)”是的,在你再次发布之前,我已经让它工作了。我也会尝试你的解决方案。谢谢你的帮助
[...]byte[] bytes = new byte[256];
sbyte[] sbytes;
while(true)
{
NetworkStream stream = client.GetStream();
int i;
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
sbytes = new sbyte[bytes.Length];
for (int j = 0; j < bytes.Length; j++)
sbytes[j] = (sbyte)bytes[j];
packetID=bytes[0]; [...]
sbyte[] signedB = new sbyte[bytes.Length];
Buffer.BlockCopy(bytes, 0, signedB, 0, bytes.Length);