C#简易网络连接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kehuduan123
{
    class Program
    {
        static void Main(string[] args)
        {
            //设置一个客户端对象
            Socket kehuduan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //设置服务器的ip地址
            IPAddress ip = IPAddress.Parse("192.168.10.100");
            //设置端口
            kehuduan.Connect(new IPEndPoint(ip,8888));
            Console.WriteLine("连接成功!");
            Program pro = new Program();
            Thread th1 = new Thread(pro.listen);
            th1.Start(kehuduan);
            Thread th2 = new Thread(pro.send);
            th2.Start(kehuduan);
            Console.ReadKey();
        }
        public void send(Object obj)
        {
            Socket s = (Socket)obj;
            while (true)
            {
                byte[] b = new byte[100];
                int n = s.Receive(b);
                string str = UTF8Encoding.UTF8.GetString(b, 0, n);
                Console.WriteLine("服务端说:" + str);
            }

        }
        public void listen(Object obj)
        {
            while (true)
            {
                Socket s = (Socket)obj;
                string str = Console.ReadLine();
                byte[] b = UTF8Encoding.UTF8.GetBytes(str);
                s.Send(b);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/allyh/p/13388599.html