从c#通过tcp与java服务器进行通信

本文关键字:服务器 通信 java 通过 tcp | 更新日期: 2023-09-27 18:24:21

我在玩TCP服务器和客户端的游戏,我试图通过c#应用程序与Java服务器通信,但我无法使其正常工作。

我的Java服务器使用多线程服务器(线程连接)。我使用DataInputStream和DataOutputStream读取输入流并编写输出流。这是我用来接收传入包裹的代码

DataInputStream ois = null;
DataOutputStream oos = null;

ois  = new DataInputStream(clientSocket.getInputStream());
oos = new DataOutputStream(clientSocket.getOutputStream());

        while(clientSocket.isConnected())
        {
            while(ois.available() > 0)
            {
                byte id = ois.readByte();
                Package p = MultiThreadedServer.getPackageHandler().getPackage(id);
                if(p != null)
                {
                    p.handle(ois, oos);
                    System.out.println("Request processed with id: " + id);
                }
              }
          }

当我通过java连接到这个服务器时,我习惯于用这种方式发送数据:

DataOutputStream oos = new DataOutputStream(socket.getOutputStream());
oos.writeByte(5);
oos.writeByte(3); // user_ID
oos.flush();

然后,我在服务器中搜索一个包,该包的id与发送oos.writeByte(5)的传入字节相同;这是我的包裹类

    public abstract class Package
{
    private int id = 0;
    public Package(int id){ this.id = id; }
    public abstract void handle(DataInputStream ois, DataOutputStream oos) throws Exception;
    public int getID()
    {
        return id;
    }
}

我如何读取传入数据的示例:

@Override
                    public void handle(DataInputStream ois, DataOutputStream oos) throws Exception
                    {
                        int user_id = ois.readByte();
                        System.out.println("Handle package 1 " + user_id);
                        ResultSet rs = cm.execute("SELECT TOP 1 [id] ,[username] FROM [Database].[dbo].[users] WHERE [id] = '"+ user_id +"'");
                        while (rs.next())
                        {
                            oos.writeByte((getID() + (byte)999));
                            oos.writeUTF(rs.getString(2));
                            oos.flush();
                        }
                    }

这在Java中运行良好,但我如何使用c#发送这样的数据?我需要一个可以做到这一点的功能:

DataOutputStream oos = new DataOutputStream(socket.getOutputStream());
    oos.writeByte(5);
    oos.writeByte(3); // user_ID
    oos.flush();

或者其他什么,但在c#中,但c#中的NetworkStream类不支持这一点,所以我该怎么做?

从c#通过tcp与java服务器进行通信

我看不出C#中的NetworkStream不支持什么。在构造函数中传递套接字,并使用WriteByte()发送数据。Flush()也可用。

所以它看起来是这样的:

var oos = new NetworkStream(socket);
oos.WriteByte(5);
oos.WriteByte(3); // user_ID
oos.Flush();

要编写浮点或双精度,您必须自己转换它们:

double a = 1.1;
long a_as_long = BitConverter.DoubleToInt64Bits(a);
byte[] a_as_bytes = BitConverter.GetBytes(a_as_long);
oos.Write(a_as_bytes, 0, a_as_bytes.Length)