C# Socket

 

-------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

/// <summary>
/// 服务端
/// </summary>

namespace SocketServerTest
{
  class Program
  {
    private static byte[] result = new byte[1024];
    private static int myProt = 5209; //端口
    static Socket serverSocket;
    static void Main(string[] args)
    {
      //服务器IP地址
      IPAddress ip = IPAddress.Parse("127.0.0.1");
      serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      //serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口 

      serverSocket.Bind(new IPEndPoint(IPAddress.Any, myProt)); //绑定IP地址:端口  (正常情况下,客户端和服务端不在一台机器上,所以使用IPAddress.Any就表示任何客户端都可以连接到该服务端)
      serverSocket.Listen(10); //设定最多10个排队连接请求
      Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
      Socket clientSocket = serverSocket.Accept();
      while (true) {
          Thread.Sleep(1000);
          SendMsg(clientSocket);
      }
    }

    /// <summary>
    /// 以每秒一次的频率发送数据给客户端
    /// </summary>
    /// <param name="clientSocket"></param>
    public static void SendMsg(Socket clientSocket)
    {
      try
      {
        clientSocket.Send(Encoding.ASCII.GetBytes(GetRandomData()));
      }
      catch {
        Console.WriteLine("服务器异常");
        return;
      }
    }

    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="clientSocket"></param>
    private static void ReceiveMessage(object clientSocket)
    {
      Socket myClientSocket = (Socket)clientSocket;
      while (true)
      {
        try
        {
          //通过clientSocket接收数据
          int receiveNumber = myClientSocket.Receive(result);
          Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
          myClientSocket.Shutdown(SocketShutdown.Both);
          myClientSocket.Close();
          break;
        }
      }
    }

    /// <summary>
    /// 产生随机字符串
    /// </summary>
    /// <returns></returns>
    private static string GetRandomData()
    {
        Random ran = new Random();
        int x = ran.Next(50,200);
        int y = ran.Next(20,100);
        int z = 1000;
        int ID = ran.Next(1,30);
        string str = "ID:"+ID+"-x:"+x+"-y:"+y+"-z:"+z;
        return str;
    }

  }
}

---------------------------------------------------------------------------------------------------------

客户端

---------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
/// <summary>
/// 客户端
/// </summary>
namespace SocketTest1
{
  class Program
  {
    private static byte[] result = new byte[1024];
    static void Main(string[] args)
    {
      //设定服务器IP地址
      IPAddress ip = IPAddress.Parse("127.0.0.1");
      Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      try
      {
        clientSocket.Connect(new IPEndPoint(ip, 5209)); //配置服务器IP与端口
        Console.WriteLine("连接服务器成功");
      }
      catch
      {
        Console.WriteLine("连接服务器失败,请按回车键退出!");
        return;
      }
      //通过clientSocket接收数据
      while (true) {
            int receiveLength = clientSocket.Receive(result);
            Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
      }

      //通过 clientSocket 发送数据
      //for (int i = 0;i <10; i++)
      //{
      //  try
      //  {
      //    Thread.Sleep(1000);
      //    string sendMessage = "client send Message Hellp" + DateTime.Now;
      //    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
      //    Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
      //  }
      //  catch
      //  {
      //    clientSocket.Shutdown(SocketShutdown.Both);
      //    clientSocket.Close();
      //    break;
      //  }
      //}

      //Console.WriteLine("发送完毕,按回车键退出");
      //Console.ReadLine();
    }
  }
}

posted @ 2017-06-20 14:47  西北逍遥  阅读(268)  评论(0编辑  收藏  举报