1.编写服务端代码,以原石兑换码为例(分别建立两个控制台应用,一个用于服务端,一个用于客户端)
using System.Net.Sockets;
using System.Net;
using System.Text;
namespace 网络游戏服务器
{
internal class Program
{
static void Main(string[] args)
{
Socket mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化
IPAddress myIp = IPAddress.Parse("127.0.0.1");//指定IP
IPEndPoint myPoint = new IPEndPoint(myIp, 8000);//指定IP和端口
mysocket.Bind(myPoint);//开机
mysocket.Listen(8);//监听
//模拟兑换码
string x = "114514";
while (true)
{
Console.WriteLine("Start Accept");
Socket clientSocket = mysocket.Accept();//应答
while (true)
{
byte[] myBuff = new byte[1024];
int recNum = clientSocket.Receive(myBuff);
string recStr = Encoding.UTF8.GetString(myBuff, 0, recNum);//转换接受的格式
Console.WriteLine("收到来自客户端的消息" + recStr);//把接收到的消息打印出来
if (recStr == x)
{
Console.WriteLine("收到兑换码请求");
string reply = "恭喜你兑换成功,获得原石8848颗";
byte[] data = Encoding.UTF8.GetBytes(reply); //编码回复消息
// 发送回复消息给客户端
clientSocket.Send(data);
}
else
{
string reply2 = "无效的兑换码,请检查输入";
byte[] data = Encoding.UTF8.GetBytes(reply2); //编码回复消息
// 发送回复消息给客户端
clientSocket.Send(data);
}
if (recStr == "exit")
{
break; // 如果接收到 "exit",跳出内层循环,断开连接并等待下一个连接
}
}
}
}
}
}
2.编写客户端代码
using System.Net.Sockets;
using System.Net;
using System.Text;
namespace 网络游戏客户端
{
internal class Program
{
static void Main(string[] args)
{
Socket mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化
IPAddress myIp = IPAddress.Parse("127.0.0.1");//指定ip
IPEndPoint myPoint = new IPEndPoint(myIp, 8000);//指定ip和端口
mysocket.Connect(myPoint); // 建立与目标主机的连接
while (true)
{
Console.WriteLine("请输入原石兑换码");
string sendstr = Console.ReadLine();
byte[] sendBts = Encoding.UTF8.GetBytes(sendstr);//设置发送的格式
mysocket.Send(sendBts); // 发送数据
byte[] receiveBuffer = new byte[1024]; // 缓冲区大小可以根据需要调整
int receiveLength = mysocket.Receive(receiveBuffer); // 接收数据
string receivedData = Encoding.UTF8.GetString(receiveBuffer, 0, receiveLength); // 将接收到的字节数据转换为字符串
Console.WriteLine("来自服务器的数据: " + receivedData); // 打印接收到的数据
if (sendstr == "exit")
{
break; // 输入exit时退出循环
}
}
}
}
}
3.先运行服务端再运行客户端,就能实现客户端和服务端的通信了(注意顺序不能错,错了客户端连接不了服务器会报错)