• TCP,UDP 通讯的helper类


    使用Tcp通讯,首先要启动tcp服务端监听客户端,客户端发送消息,服务端收到消息

    1.服务端代码如下


    public class TcpServerTest
    {
    public async Task BeginServerAsync()
    {
    TcpClient client = null;
    NetworkStream stream = null;
    byte[] buffer = null;
    string receiveString = null;

    IPAddress localIP = IPAddress.Parse("127.0.0.1");
    int localPort = 11000;
    TcpListener listener = new TcpListener(localIP, localPort);//用本地IP和端口实例化Listener
    listener.Start();//开始监听
    while (true)
    {
    client = await listener.AcceptTcpClientAsync();//接受一个Client
    buffer = new byte[client.ReceiveBufferSize];
    stream = client.GetStream();//获取网络流
    stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据
    stream.Close();//关闭流
    client.Close();//关闭Client

    receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串
    Console.WriteLine(receiveString);
    }
    }

    2.TCPClient客户端代码如下

    public class TcpClientTest
    {

    public void BeginClient()
    {
    string sendString = null;//要发送的字符串
    byte[] sendData = null;//要发送的字节数组
    System.Net.Sockets.TcpClient client = null;//TcpClient实例
    NetworkStream stream = null;//网络流

    IPAddress remoteIP = IPAddress.Parse("127.0.0.1");//远程主机IP
    int remotePort = 11000;//远程主机端口

    while (true)//死循环
    {
    sendString = Console.ReadLine();//获取要发送的字符串
    sendData = Encoding.Default.GetBytes(sendString);//获取要发送的字节数组
    client = new System.Net.Sockets.TcpClient();//实例化TcpClient
    try
    {
    client.Connect(remoteIP, remotePort);//连接远程主机
    }
    catch (System.Exception ex)
    {
    Console.WriteLine("连接超时,服务器没有响应!");//连接失败
    Console.ReadKey();
    return;
    }
    stream = client.GetStream();//获取网络流
    stream.Write(sendData, 0, sendData.Length);//将数据写入网络流
    stream.Close();//关闭网络流
    client.Close();//关闭客户端
    }
    }

  • 相关阅读:
    python虚拟环境--virtualenv
    python使用smtplib发送邮件
    python网络编程
    python操作MySQL数据库
    python面向对象
    python内置函数总结
    python异常处理
    python文件I/O
    python模块
    python函数
  • 原文地址:https://www.cnblogs.com/xiaohouye/p/11134214.html
Copyright © 2020-2023  润新知