zoukankan      html  css  js  c++  java
  • Socket

    服务器端 

      public class SocketServer

        {

            private string _ip = string.Empty;

            private int _port = 0;

            private Socket _socket = null;

            private byte[] buffer = new byte[1024 * 1024 * 2];

            /// <summary>

            /// 构造函数

            /// </summary>

            /// <param name="ip">监听的IP</param>

            /// <param name="port">监听的端口</param>

            public SocketServer(string ip, int port)

            {

                this._ip = ip;

                this._port = port;

            }

            public SocketServer(int port)

            {

                this._ip = "0.0.0.0";

                this._port = port;

            }

            public void StartListen()

            {

                try

                {

                    //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)

                    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    //2.0 创建IP对象

                    IPAddress address = IPAddress.Parse(_ip);

                    //3.0 创建网络端口,包括ip和端口

                    IPEndPoint endPoint = new IPEndPoint(address, _port);

                    //4.0 绑定套接字

                    _socket.Bind(endPoint);

                    //5.0 设置最大连接数

                    _socket.Listen(int.MaxValue);

                    Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString());

                    //6.0 开始监听

                    Thread thread = new Thread(ListenClientConnect);

                    thread.Start();

                }

                catch (Exception ex)

                {

                }

            }

            /// <summary>

            /// 监听客户端连接

            /// </summary>

            private void ListenClientConnect()

            {

                try

                {

                    while (true)

                    {

                        //Socket创建的新连接

                        Socket clientSocket = _socket.Accept();

                        clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));

                        Thread thread = new Thread(ReceiveMessage);

                        thread.Start(clientSocket);

                    }

                }

                catch (Exception)

                {

                }

            }

            /// <summary>

            /// 接收客户端消息

            /// </summary>

            /// <param name="socket">来自客户端的socket</param>

            private void ReceiveMessage(object socket)

            {

                Socket clientSocket = (Socket)socket;

                int i=0;

                while (true)

                {

                    try

                    {

                        //获取从客户端发来的数据

                        int length = clientSocket.Receive(buffer);

                        Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));

                        clientSocket.Send(Encoding.UTF8.GetBytes((i++).ToString()));

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.Message);

                        clientSocket.Shutdown(SocketShutdown.Both);

                        clientSocket.Close();

                        break;

                    }

                }

            }

        }

    客户端 

      public class SocketClient

        {

            private string _ip = string.Empty;

            private int _port = 0;

            private Socket _socket = null;

            private byte[] buffer = new byte[1024 * 1024 * 2];

            /// <summary>

            /// 构造函数

            /// </summary>

            /// <param name="ip">连接服务器的IP</param>

            /// <param name="port">连接服务器的端口</param>

            public SocketClient(string ip, int port)

            {

                this._ip = ip;

                this._port = port;

            }

            public SocketClient(int port)

            {

                this._ip = "127.0.0.1";

                this._port = port;

            }

            /// <summary>

            /// 开启服务,连接服务端

            /// </summary>

            public void StartClient()

            {

                try

                {

                    //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)

                    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    //2.0 创建IP对象

                    IPAddress address = IPAddress.Parse(_ip);

                    //3.0 创建网络端口包括ip和端口

                    IPEndPoint endPoint = new IPEndPoint(address, _port);

                    //4.0 建立连接

                    _socket.Connect(endPoint);

                    Console.WriteLine("连接服务器成功");

                    //5.0 接收数据

                    int length = _socket.Receive(buffer);

                    Console.WriteLine("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));

                    //6.0 像服务器发送消息

                    for (int i = 0; i < 10; i++)

                    {

                        Thread.Sleep(2000);

                        string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());

                        _socket.Send(Encoding.UTF8.GetBytes(sendMessage));

                        length=_socket.Receive(buffer);

                        Console.WriteLine("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));

                        Console.WriteLine("像服务发送的消息:{0}", sendMessage);

                    }

                }

                catch (Exception ex)

                {

                    _socket.Shutdown(SocketShutdown.Both);

                    _socket.Close();

                    Console.WriteLine(ex.Message);

                }

                Console.WriteLine("发送消息结束");

                Console.ReadKey();

            }

        }

    服务器端:

     static void Main(string[] args)

            {

                SocketServer server = new SocketServer(8888);

                server.StartListen();

                Console.ReadKey();

            }

    客户端 :

           SocketClient client = new SocketClient(8888);

                client.StartClient();

                Console.ReadKey();

    1. using System;
    2.  
      using System.Collections.Generic;
    3.  
      using System.Linq;
    4.  
      using System.Net;
    5.  
      using System.Net.Sockets;
    6.  
      using System.Text;
    7.  
      using System.Threading;
    8.  
       
    9.  
      namespace SocketUtil
    10.  
      {
    11.  
      public class SocketServer
    12.  
      {
    13.  
      private string _ip = string.Empty;
    14.  
      private int _port = 0;
    15.  
      private Socket _socket = null;
    16.  
      private byte[] buffer = new byte[1024 * 1024 * 2];
    17.  
      /// <summary>
    18.  
      /// 构造函数
    19.  
      /// </summary>
    20.  
      /// <param name="ip">监听的IP</param>
    21.  
      /// <param name="port">监听的端口</param>
    22.  
      public SocketServer(string ip, int port)
    23.  
      {
    24.  
      this._ip = ip;
    25.  
      this._port = port;
    26.  
      }
    27.  
      public SocketServer(int port)
    28.  
      {
    29.  
      this._ip = "0.0.0.0";
    30.  
      this._port = port;
    31.  
      }
    32.  
       
    33.  
      public void StartListen()
    34.  
      {
    35.  
      try
    36.  
      {
    37.  
      //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
    38.  
      _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    39.  
      //2.0 创建IP对象
    40.  
      IPAddress address = IPAddress.Parse(_ip);
    41.  
      //3.0 创建网络端口,包括ip和端口
    42.  
      IPEndPoint endPoint = new IPEndPoint(address, _port);
    43.  
      //4.0 绑定套接字
    44.  
      _socket.Bind(endPoint);
    45.  
      //5.0 设置最大连接数
    46.  
      _socket.Listen(int.MaxValue);
    47.  
      Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString());
    48.  
      //6.0 开始监听
    49.  
      Thread thread = new Thread(ListenClientConnect);
    50.  
      thread.Start();
    51.  
       
    52.  
      }
    53.  
      catch (Exception ex)
    54.  
      {
    55.  
      }
    56.  
      }
    57.  
      /// <summary>
    58.  
      /// 监听客户端连接
    59.  
      /// </summary>
    60.  
      private void ListenClientConnect()
    61.  
      {
    62.  
      try
    63.  
      {
    64.  
      while (true)
    65.  
      {
    66.  
      //Socket创建的新连接
    67.  
      Socket clientSocket = _socket.Accept();
    68.  
      clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));
    69.  
      Thread thread = new Thread(ReceiveMessage);
    70.  
      thread.Start(clientSocket);
    71.  
      }
    72.  
      }
    73.  
      catch (Exception)
    74.  
      {
    75.  
      }
    76.  
      }
    77.  
       
    78.  
      /// <summary>
    79.  
      /// 接收客户端消息
    80.  
      /// </summary>
    81.  
      /// <param name="socket">来自客户端的socket</param>
    82.  
      private void ReceiveMessage(object socket)
    83.  
      {
    84.  
      Socket clientSocket = (Socket)socket;
    85.  
      while (true)
    86.  
      {
    87.  
      try
    88.  
      {
    89.  
      //获取从客户端发来的数据
    90.  
      int length = clientSocket.Receive(buffer);
    91.  
      Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));
    92.  
      }
    93.  
      catch (Exception ex)
    94.  
      {
    95.  
      Console.WriteLine(ex.Message);
    96.  
      clientSocket.Shutdown(SocketShutdown.Both);
    97.  
      clientSocket.Close();
    98.  
      break;
    99.  
      }
    100.  
      }
    101.  
      }
    102.  
      }
    103.  
      }
  • 相关阅读:
    学习python第二天
    学习python第一天
    SQL操作
    JAR规范 JAR File Specification
    IDEA快捷键
    Fibonacci数列
    AnyHandler
    测试UDP
    Eclipse卡顿设置
    服务器初始化操作
  • 原文地址:https://www.cnblogs.com/hanzonghao/p/14247419.html
Copyright © 2011-2022 走看看