【问题标题】:Server client communication using Socket C#使用 Socket C# 的服务器客户端通信
【发布时间】:2020-08-04 06:22:54
【问题描述】:

我创建了一个应用程序,它使用 IP/端口与服务器通信。它正在发送 ISO 请求字符串(ASCII 格式的位图)并接收相同格式的响应字符串。通过 socket.send 发送字节并在 socket.receive 方法中接收字节。我可以看到扩展的 ASCII 字符在另一端(服务器端/克林特端)发生了变化。我正在使用下面的代码。任何人都可以建议,如何解决这个问题。

IPAddress ipAddr = IPAddress.Parse("10.03.0.18");               

IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 12345);            

// Creation TCP/IP Socket using  
// Socket Class Costructor 
Socket sender = new Socket(ipAddr.AddressFamily,SocketType.Stream, ProtocolType.Tcp);             

sender.Connect(localEndPoint);
string requeststring = AccountValidationRequest();              

byte[] messageSent = Encoding.ASCII.GetBytes(requeststring);

int byteSent = sender.Send(messageSent);

byte[] ServerResponse = new byte[1024];
int byteRecv = sender.Receive(ServerResponse); 
string ISO8583Message = Encoding.ASCII.GetString(ServerResponse, 0, byteRecv);

Console.WriteLine("Response received from server: --> :{0}", Encoding.ASCII.GetString(ServerResponse, 0, byteRecv));

【问题讨论】:

  • 究竟要改成什么?请显示一些前后文本的示例。
  • 另外,请问服务器端的代码在哪里?也许它故意改变它?您是否希望完全原封不动地恢复数据?
  • 不要假设您收到的是一大块消息。用 '\n' 终止每条 ascii 消息,并在收到后确保在处理之前得到 '\n'。
  • 服务器正在向我发送一些 ASCII 格式的二进制字符串掩码,当我在我的应用程序中解码该 ASCII 时,我得到了不同的二进制字符串。例如服务器发送:(原始二进制)ASCII格式11110000001100001000000000000001000011101000000110000000000000000000000000000000000000000000000000000000000000000000000000111110发送解码我收到之后:00111111001100000011111100000001000011100011111100111111000000000000000000000000000000000000000000000000000000000000000000111110 跨度>
  • 这是我们现在越来越:位图我送的11110000001100001000000100000001000010000010000010000000000000000000000000000000000000000000000000000100000000000000000000110100服务器得到它在解码00111111001100000011111100000001000010000010000000111111000000000000000000000000000000000000000000000100000000000000000000110100后做你看到它的任何解决方案 SPAN>

标签: c# sockets client-server ascii


【解决方案1】:

正如 cmets 中建议的那样,您应该断言您读取所有数据,而不仅仅是第一个块。

Byte[] bytesReceived = new Byte[256];
int bytes = 0;

var ISO8583Message = "Response: \n";
do {
    bytes = sender.Receive(bytesReceived, bytesReceived.Length, 0);
    ISO8583Message = ISO8583Message + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

有一些在https://docs.microsoft.com/pl-pl/dotnet/api/system.net.sockets.socket?view=netframework-4.8 上使用套接字的好例子。

【讨论】:

  • 我一次收到批量响应(388 字节)。我正在与之通信的服务器有一个正在运行的应用程序。所以他们不会改变他们的代码。我只能修改我的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2016-10-29
  • 1970-01-01
  • 2015-12-25
相关资源
最近更新 更多