简体   繁体   English

服务器客户端通信使用 Socket C#

[英]Server client communication using Socket C#

I have created an application, which is communicating a server using IP/port.我创建了一个应用程序,它使用 IP/端口与服务器通信。 It is sending a ISO request string(Bitmaps in ASCII format) and receiving a response string same format.它正在发送 ISO 请求字符串(ASCII 格式的位图)并接收相同格式的响应字符串。 While Sending the bytes through socket.send and receiving the bytes in socket.receive method.通过 socket.send 发送字节并在 socket.receive 方法中接收字节。 I can see extended ASCII characters are getting changed on other side (Server side/Clint side).我可以看到扩展的 ASCII 字符在另一端(服务器端/克林特端)发生了变化。 I am using below code.我正在使用下面的代码。 Can anyone suggest please, How to resolve the issue.任何人都可以建议,如何解决这个问题。

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));

As it was suggested in comments you should assert that you read all data, not only the first chunk.正如评论中建议的那样,您应该断言您读取了所有数据,而不仅仅是第一个块。

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);

There are some nice examples with using sockets on https://docs.microsoft.com/pl-pl/dotnet/api/system.net.sockets.socket?view=netframework-4.8 .在 https 上使用 sockets 有一些很好的例子://docs.microsoft.com/pl-pl/dotnet/api/system.net.sockets.socket?view=netframework-8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM