• SocketTCPBase


     

    suggested use Asynchronous Programming(Async Task)

     

    Server:

    int connectCount = 0;
    Console.WriteLine("wait for conncet...");
    Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = new IPAddress(new byte[] {192,168,2,103 });
    IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788);
    tcpServer.Bind(endPoint);
    tcpServer.Listen(100); 
    var client= tcpServer.Accept();
    
    Console.WriteLine($"conncet:{++connectCount}{client.AddressFamily.ToString()}");
    byte[] data = new byte[1024];
    int len= client.Receive(data);
    Console.WriteLine(Encoding.UTF8.GetString(data,0,len));
    string ServerMessage = "Server Send Message to Client";
    Console.WriteLine($"Send:{ServerMessage}");
    client.Send(Encoding.UTF8.GetBytes(ServerMessage));
    
    client.Close();
    tcpServer.Close();
    Console.ReadLine();

    Client:

    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 2, 103 });//IP
    IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788);//port
    tcpClient.Connect(endPoint); //connect
    Console.WriteLine("connect..");
    string sendMessage = "line";
    Console.WriteLine($"send:{sendMessage}...");
    tcpClient.Send(Encoding.UTF8.GetBytes(sendMessage));//send
    
    
    byte[] data = new byte[1024];
    int len = tcpClient.Receive(data);
    Console.WriteLine($"Server:{Encoding.UTF8.GetString(data, 0, len)}");
  • 相关阅读:
    颜色透明度16进制对照表
    爬取代理IP
    Python中匹配IP的正则表达式
    IP地址正则表达式的写法
    每日一练 11.23
    每日一练 11.22
    每日一练
    pycharm使用教程
    周总结博客16
    周总结博客15
  • 原文地址:https://www.cnblogs.com/Zingu/p/16369357.html
Copyright © 2020-2023  润新知