client:
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace GameClient
{
class Program
{
static void Main(string[] args)
{
//連接
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(IPAddress.Parse("192.168.1.104"), 4444);
//接受服務器連接消息
byte[] data = new byte[1024];
int count = clientSocket.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, count);
Console.WriteLine(msg);
//while (true)
//{
// string s = Console.ReadLine();
// if (s == "c")
// {
// clientSocket.Close();
// break;
// }
// byte[] buffer = Encoding.UTF8.GetBytes(s);
// clientSocket.Send(buffer);
//}
//發送消息檢測粘包
Console.ReadKey();
for (int i = 0; i < 100; i++)
{
clientSocket.Send(Message.GetBytes(i.ToString()));
// clientSocket.Send(Encoding.UTF8.GetBytes(i.ToString()));
}
Console.ReadKey();
}
}
class Message
{
//數據簡單封裝(消息長度+消息躰)
public static byte[] GetBytes(string data)
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
int count = buffer.Length;
byte[] countBuffer = BitConverter.GetBytes(count);
byte[] newBuffer = countBuffer.Concat(buffer).ToArray();
return newBuffer;
}
}
}
server:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace GameServer
{
class Program
{
static void Main(string[] args)
{
StartServerAsync();
Console.ReadKey();
}
// static byte[] buffer = new byte[1024];
static Message myMsg = new Message();
static void StartServerAsync()
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("192.168.1.104");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 4444);
serverSocket.Bind(ipEndPoint);//绑定ip和端口
serverSocket.Listen(10);//监听
serverSocket.BeginAccept(AcceptCallback,serverSocket);//異步接收客戶端連接
}
static void AcceptCallback(IAsyncResult ar)
{
Socket serverSocket = ar.AsyncState as Socket;
Socket clientSocket = serverSocket.EndAccept(ar);
//向客户端发送一个連接消息
string msg = "服務器:你好,客户端已連接服務器 - "+ clientSocket.RemoteEndPoint;
byte[] data = Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
//異步接受數據
clientSocket.BeginReceive(myMsg.Data, myMsg.StartIndex, myMsg.RemainMsg, SocketFlags.None, ReciveCallback, clientSocket);
serverSocket.BeginAccept(AcceptCallback, serverSocket);//接收客戶端連接
}
//異步接收數據
static void ReciveCallback(IAsyncResult ar)
{
Socket clientSocket = null;
try
{
clientSocket = ar.AsyncState as Socket;
int count = clientSocket.EndReceive(ar);//消息長度
if (count == 0)
{
clientSocket.Close();
return;
}
myMsg.AddCount(count);
myMsg.AnalysisMsg(clientSocket);//解析數據
//string msg = Encoding.UTF8.GetString(buffer, 0, count);
//Console.WriteLine("客戶端{0}-服務器:{1}", (clientSocket.RemoteEndPoint as IPEndPoint).Address, msg);
clientSocket.BeginReceive(myMsg.Data, myMsg.StartIndex, myMsg.RemainMsg, SocketFlags.None, ReciveCallback, clientSocket);
//clientSocket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ReciveCallback, clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
if (clientSocket != null)
{
clientSocket.Close();
}
}
}
void StartServerSync()
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("192.168.1.104");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 4444);
serverSocket.Bind(ipEndPoint);//绑定ip和端口
serverSocket.Listen(10);//监听
Socket clientSocket = serverSocket.Accept();//接收客戶端
//向客户端发送一个消息
string msg = "你好,客户端.";
byte[] data = Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
//服务器接受一个消息
byte[] dataBuffer = new byte[1024];
int count = clientSocket.Receive(dataBuffer);
string clientMsg = Encoding.UTF8.GetString(dataBuffer, 0, count);
Console.WriteLine(clientMsg);
Console.ReadKey();
clientSocket.Close();
serverSocket.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace GameServer
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;
//消息躰
public byte[] Data
{
get
{
return data;
}
}
//空餘空間的開始索引(消息長度)
public int StartIndex
{
get
{
return startIndex;
}
}
//剩餘空間
public int RemainMsg
{
get
{
return data.Length - startIndex;
}
}
//接收到消息時更新空餘空間的開始索引
public void AddCount(int count)
{
startIndex += count;
}
//解析
public void AnalysisMsg(Socket clientSocket)
{
while (true)
{
if (startIndex <= 4) return;
int count = BitConverter.ToInt32(data, 0);//獲取消息躰長度
if ((startIndex - 4) >= count)
{
string msgData = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("客戶端{0}-服務器:{1}", (clientSocket.RemoteEndPoint as IPEndPoint).Address, msgData);
//Console.WriteLine("客戶端-服務器", msgData);
Array.Copy(data, 4 + count, data, 0, startIndex - 4 - count);
startIndex -= (4 + count);
}
else
{
break;
}
}
}
}
}
来源:CSDN
作者:wsrq
链接:https://blog.csdn.net/ws19940118/article/details/104556314