[英]C# Send information over TCP
I'm still learning C#, so don't yell at me for not doing anything right. 我仍在学习C#,所以不要对我做的不正确大喊大叫。 Also, i know I should probably be using WPF, but in my current condition I need to use winForms.
另外,我知道我可能应该使用WPF,但是在当前条件下,我需要使用winForms。
Client: 客户:
public void sendData(String dataIn)
{
String IP = textBox1.Text;
String Port = textBox2.Text;
net.Send(dataIn, IP, Port);
}
Server: 服务器:
public string listenForData()
{
String dataOut = net.Listen();
return dataOut;
}
How do I create a method that takes a string and sends it to a server application. 如何创建一个采用字符串并将其发送到服务器应用程序的方法。 I know it has something to do with TCP sockets.
我知道它与TCP套接字有关。 I've looked but I don't understand any tutorials or videos i've found.
我已经看过,但不了解所找到的任何教程或视频。
Thanks in advance, Noah.
在此先感谢,诺亚。
You could try looking into the TCP Client Class. 您可以尝试查看TCP客户端类。
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx https://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcpclient(v=vs.110).aspx
You can get the stream from tcp client and use that to write your string to, by converting the string to a byte[] first. 您可以从tcp客户端获取流并将其写入字符串,方法是先将字符串转换为byte []。
// Setup TCP Client with valid values first. Make Client and stream private or public variables/properties.
TCPClient client = new TCPClient(IP, (int)Port); // Following validation on Port & IP
NetworkStream stream = client.GetStream();
private void SendDataToServer(String dataIn) {
Byte[] StringToSend = Encoding.UTF8.GetBytes(dataIn);
stream.Write(StringToSend, 0, StringToSend.Length);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.