[英]C# send/receive from socket
我想從服務器發送和接收一些數據,但是我不知道該怎么做...
基本上我想:發送:“一些字符串”到:IP:10.100.200.1端口:30000
接收/讀取回復
有人可以給我一些基本的例子,也可以給我指出一個簡單的(有效的)教程嗎?
簡單同步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();
}
}
您的問題有點廣泛,可以通過谷歌搜索輕松回答。
您正在尋找的東西稱為Socket
。 但是在您的情況下,我將使用TcpClient
因為它使處理更加容易。
Google“ TcpClient
c#”,您將找到一些不錯的示例。 如果您無法正常工作,請再提出一些更具體的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.