[英]C# send/receive from socket
I want to send and receive some data from my server, but I don't know how to do this... 我想从服务器发送和接收一些数据,但是我不知道该怎么做...
Basically I want to: Send: "some string" To: IP: 10.100.200.1 Port: 30000 基本上我想:发送:“一些字符串”到:IP:10.100.200.1端口:30000
Receive/read the response 接收/读取回复
Can someone give me some basic example or point me to a simple (working) tutorial? 有人可以给我一些基本的例子,也可以给我指出一个简单的(有效的)教程吗?
Simple synchronous TcpClient sending a text string and receiving a text string. 简单同步TcpClient发送文本字符串并接收文本字符串。
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class SimpleTcpClient {
public static void Main() {
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("10.100.200.1",30000);
String textToSend = "HelloWorld!";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data = asen.GetBytes(textToSend);
stm.Write(data,0,data.Length);
//You might want to wait a bit for an answer (Thread.Sleep or simething)
byte[] responseData = new byte[1024];
string textRecevided = "";
int read = 0;
do {
read = stm.Read(responseData, 0, responseData.Length);
for (int i=0; i < read; i++)
{
textRecevided += (char)responseData[i];
}
} while (read > 0);
Console.Write(textRecevied);
tcpclnt.Close();
}
}
Your question is a bit broad and it could easily be answered by googling. 您的问题有点广泛,可以通过谷歌搜索轻松回答。
The thing that you are looking for is called a Socket
. 您正在寻找的东西称为Socket
。 But in your case I would use a TcpClient
since it makes the handling a bit easier. 但是在您的情况下,我将使用TcpClient
因为它使处理更加容易。
Google " TcpClient
c#" and you'll find some nice examples. Google“ TcpClient
c#”,您将找到一些不错的示例。 Then come back with more specific questions if you can't get stuff working. 如果您无法正常工作,请再提出一些更具体的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.