8.前面篇章的代码
程序员文章站
2024-01-04 14:46:10
...
这里贴出前面篇章的所有代码:
Server端
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
StartServerASync();
Console.ReadKey();
}
static void StartServerASync()
{
string ipStr = "127.0.0.1";
int port = 888;
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress iPAddress = IPAddress.Parse(ipStr);
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
serverSocket.Bind(iPEndPoint);
serverSocket.Listen(0); // 0-表示处理连接数不受限制
//Socket clientSocket = serverSocket.Accept(); // 接受一个客户端连接
serverSocket.BeginAccept(AcceptCallBackAsync, serverSocket);
}
static Message msg = new Message();
static void AcceptCallBackAsync(IAsyncResult ar)
{
Socket serverSocket = ar.AsyncState as Socket;
Socket clientSocket = serverSocket.EndAccept(ar);
/// 向客户端发送一条消息
string msgStr = "你好,Client!";
byte[] data = Encoding.UTF8.GetBytes(msgStr);
clientSocket.Send(data);
clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);
// 继续处理下一个客户端连接
serverSocket.BeginAccept(AcceptCallBackAsync, serverSocket);
}
//static int buffSize = 1024;
//static byte[] dataBuffer = new byte[buffSize];
static void ReceiveCallBack(IAsyncResult ar)
{
Socket clientSocket = null;
try
{
clientSocket = ar.AsyncState as Socket;
int count = clientSocket.EndReceive(ar);
if (count == 0)
{
clientSocket.Close();
Console.WriteLine("客户端主动关闭连接");
return;
}
Console.WriteLine("客户端消息长度:"+count);
msg.AddCount(count);
msg.ReadMessage();
//string msgStr = Encoding.UTF8.GetString(dataBuffer, 0, count);
//Console.WriteLine("从客户端接收到数据:" + count + ":" + msgStr);
// 继续接受消息
clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
if (clientSocket != null)
{
clientSocket.Close();
}
}
}
}
}
//static void StartServerSync()
//{
// string ipStr = "127.0.0.1";
// int port = 888;
// Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// IPAddress iPAddress = IPAddress.Parse(ipStr);
// IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
// serverSocket.Bind(iPEndPoint);
// serverSocket.Listen(0); // 0-表示处理连接数不受限制
// Socket clientSocket = serverSocket.Accept(); // 接受一个客户端连接
// /// 向客户端发送一条消息
// string msg = "你好,Client!";
// byte[] data = Encoding.UTF8.GetBytes(msg);
// clientSocket.Send(data);
// // 接受客户端的一条消息
// byte[] dataBuffer = new byte[1024];
// int count = clientSocket.Receive(dataBuffer);
// string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0, count);
// Console.WriteLine("{0} -- {1}", count, msgReceive);
// Console.ReadKey();
// clientSocket.Close(); // 关闭与客户端的连接
// serverSocket.Close();
//}
Message.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TCPServer
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;
public void AddCount(int count)
{
startIndex += count;
}
public byte[] Data
{
get { return data; }
}
public int StartIndex
{
get { return startIndex; }
}
public int RemainSize
{
get { return (data.Length - startIndex); }
}
/// <summary>
/// 解析数据/读取数据
/// </summary>
public void ReadMessage()
{
while (true)
{
if (startIndex <= 4) return;
int count = BitConverter.ToInt32(data, 0);
if ((startIndex - 4) >= count)
{
string s = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("解析出来一条数据:" + s);
Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
startIndex -= (count + 4);
}
else
{
break;
}
}
}
}
}
Client端
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TCPClient
{
class Program
{
static void Main(string[] args)
{
string serverIPStr = "127.0.0.1";
int port = 888;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(serverIPStr), port));
// 接收服务器消息
byte[] data = new byte[1024];
int count = clientSocket.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, count);
Console.WriteLine(msg);
for (int i = 0; i < 100; i++)
{
clientSocket.Send(Message.GetBytes(i.ToString()));
}
//while (true)
//{
// //string sendMsg = Console.ReadLine();
// //if(sendMsg=="Close Client")
// //{
// // clientSocket.Close();
// // return;
// //}
//}
Console.ReadKey();
clientSocket.Close();
}
}
}
Message.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TCPClient
{
class Message
{
// 消息长度+消息体
public static byte[] GetBytes(string data)
{
Console.WriteLine(data);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
int dataLength = dataBytes.Length;
Console.WriteLine(dataLength);
byte[] lengthBytes = BitConverter.GetBytes(dataLength);
byte[] newBytes = lengthBytes.Concat(dataBytes).ToArray();
Console.WriteLine(newBytes.Length);
return newBytes;
}
}
}