Socket服务端

Posted 凡是过往,皆为序章。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        }
    }
}

 

以上是关于Socket服务端的主要内容,如果未能解决你的问题,请参考以下文章

Socket通信客户端和服务端代码

java Socket 客户端服务端对接正确写法(BIO)

ABB Server(服务端)代码解析

java怎么处理socket服务端粘包

php socket客户端及服务器端应用实例

java Socket通信