繁体   English   中英

C#从套接字发送/接收

[英]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.

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