hehexiaoxia 2017-02-16 14:47 采纳率: 100%
浏览 1055
已采纳

C#用socket发送组包给java服务器,调用recieve时ConnectionAbort。

 C#用socket发送组包给java服务器,调用recieve时ConnectionAbort。
java要求 将数据报文通过utf8编码发送。
connection和send都能通过。
调用接收直接返回0。
不知道是组包格式不对还是字节序,查资料说utf8不需要字节序,请大神帮忙分析一下。

  IPAddress ip = IPAddress.Parse("192.168.65.30");
            IPEndPoint endP = new IPEndPoint(ip, 8099);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(endP);

            byte[] face1 = converttobytes("image/1.JPG");
            byte[] face2 = converttobytes("image/1.JPG");

            byte[] magic_word = Encoding.ASCII.GetBytes("HBVE");
            int version = 1;

            byte type = 1;
            int id = 10000;

            byte type1 = 1;
            byte type2 = 1;

            int face1_len = face1.Length;
            int face2_len = face2.Length;

            int totallength = 10 + face1.Length + face2.Length + 5;

            byte[] bytes = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    //bw.Write(bytes);

                    bw.Write(magic_word);
                    bw.Write(version);
                    bw.Write(totallength);
                    bw.Write(type);
                    bw.Write(id);
                    bw.Write(type1);
                    bw.Write(type2);
                    bw.Write(face1_len);
                    bw.Write(face1);
                    bw.Write(face2_len);
                    bw.Write(face2);

                    ms.Position = 0;

                    using (BinaryReader br = new BinaryReader(ms, Encoding.UTF8))
                    {
                        bytes = br.ReadBytes((int)ms.Length);
                    }
                }
            }

            try
            {
                SocketError error = SocketError.AccessDenied;
                int result = client.Send(bytes, 0, bytes.Length, SocketFlags.None, out error);
                byte[] by = new byte[client.ReceiveBufferSize];

                result = client.Receive(by, 0, by.Length, SocketFlags.None, out error);
            }
            catch (Exception ex)
            {
                throw ex;
            }

  • 写回答

2条回答 默认 最新

  • hehexiaoxia 2017-02-17 03:35
    关注

    已经解决了,是字节序的问题。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能