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