C#操作socket

C#作为客户端的编写

private Socket socket = null;
IPEndPoint ipep;
 private bool sockConn()
 {
      try
      {
          if (socket == null)
          {
              ipep = new IPEndPoint(IPAddress.Parse(CPublic.PServerIP), Convert.ToInt32(CPublic.PServerPort));
              socket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
              socket.Connect(ipep);
              connflag = true;
          }
      }
      catch (System.Exception ex)
      {
          connflag = false;
    
      }
      return connflag;
}
简单实现客户端的定时发送心跳
//创建定时器
System.Timers.Timer heartTimer;
heartTimer = new System.Timers.Timer(10000);
heartTimer.Elapsed += heartTimer_Click;
heartTimer.Enabled = true;

static int nTime = 0;
private void heartTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if (Interlocked.Exchange(ref nTime, 1) == 0)
    {
        byte[] buf = getBufHeart();  //
        SendHeart(buf); //发送心跳包
        Interlocked.Exchange(ref nTime, 0);
    }

}

 

简单实现服务器端

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


namespace Server
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8888;   //端口
        static Socket serverSocket;
        static void Main(string[] args)
        {

            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt)); 
            serverSocket.Listen(10);   
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            string strTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine(strTime);
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            Console.ReadLine();
        }

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }

        /// <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;
                }
            }
        }

    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值