简体   繁体   English

如何通过局域网传输字符串?

[英]How to transfer a string over LAN?

I have two applications which are running on computers on a LAN. 我有两个在局域网上的计算机上运行的应用程序。 I need to transfer a string between them but I can't do this because the Socket.Send method doesn't accept a string. 我需要在它们之间传输字符串,但是我不能这样做,因为Socket.Send方法不接受字符串。 Is there any way to do this? 有什么办法吗?

transfer your String into a Byte-array with the following function: 使用以下函数将您的字符串转换为字节数组:

Encoding.UTF8.GetBytes(str)

ByteArrays can be handled by the Socket.send function. ByteArrays可以由Socket.send函数处理。

On the other side, convert your Byte-array into a string again: 另一方面,再次将字节数组转换为字符串:

Encoding.UTF8.GetString(buffer)

You can convert your string into a byte array on the fly as you send it: 您可以在发送字符串时将其转换为字节数组:

_socket.Send( System.Text.Encoding.UTF8.GetBytes( datastring ) );

At the receiving end, you convert it back into a string like this: 在接收端,将其转换回这样的字符串:

datastring = System.Text.Encoding.UTF8.GetString(
               bytesBuffer, 0, numberOfBytesReceived );

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

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