Socket服务端

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

namespace IServer {
    class Program 
    {
        static void Main(string[] args) 
        {
            try
            {
                var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[2];
                var port = 5001;
                var IPEndPoint = new IPEndPoint(host, port);
                var Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Socket.Bind(IPEndPoint);
                Socket.Listen(10);
                Console.WriteLine("等待客户端连接");
                var temp = Socket.Accept();
                Console.WriteLine("客户端已连接,地址为{0}",temp.RemoteEndPoint);

                var t1 = new Thread(new ParameterizedThreadStart(Send));
                var t2 = new Thread(new ParameterizedThreadStart(Recive));
                t1.Start(temp);
                t2.Start(temp);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            Console.ReadLine();

          }

        public static void Send(object temp)
        {
            while (true)
            {
                string sendStr = Console.ReadLine().ToString();
                byte[] bs = Encoding.Unicode.GetBytes(sendStr);
                ((Socket)temp).Send(bs, bs.Length, 0);
            }
        }

        public static void Recive(object temp)
        {
            while (true)
            {
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                var bytes = ((Socket)temp).Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                recvStr += Encoding.Unicode.GetString(recvBytes, 0, bytes);
                Console.WriteLine("Client:{0}", recvStr);//把客户端传来的信息显示出来
            }
        }

        public static void Closed(Socket Socket,Socket temp)
        {
            temp.Close();
            Socket.Close();
        }
    }
}
原文地址:https://www.cnblogs.com/fuxuyang/p/7419567.html