首页 文章

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

提问于
浏览
-1

我正在玩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);这是我的Package类

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类不支持这个,所以我该怎么做呢?

1 回答

  • 0

    我没有看到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)
    

相关问题