首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

简单服务器与客户端交互

//服务器端代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net.Sockets;

using System.Net;

using System.Threading;

using System.IO;

using LitJson;

namespace Package

{

class Server

public TcpListener tcpListener;//声明公众变量,以方便在别的方法中进行调用

public TcpClient tcpClient;

public List tcpClients = new List();//客户端的集合,多个客户端连接时,存储进集合,本篇中未使用

public List datas = new List();//封装发送接收数据的类Data

public List users = new List();//同理

public List goods = new List();

public List stores = new List();

void Start()

{

tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 5050);//绑定Ip,端口

//"127.0.0.1" 通用自身IP

tcpListener.Start(); //启动 tcpListener

Thread thread = new Thread(AcceptClient);//开启分线程,防止进程卡死

thread.Start();

}

void AcceptClient()

{

try

{

while (true)//一直在循环判断状态

{

if (tcpListener.Pending())//判定是否有客户端连接

{

//获取本地json文件,这三个可以封装成一个方法,我没封装

tcpClient = tcpListener.AcceptTcpClient();

if (GetData()!=null)

{

users = JsonMapper.ToObject

>(GetData());

}

if (GetDataGoods() != null)

{

goods = JsonMapper.ToObject

>(GetDataGoods());

}

if (GetDataStores() != null)

{

stores = JsonMapper.ToObject

>(GetDataStores());

}

Console.WriteLine("客户端接入");

Data data = new Data(tcpClient,this);

datas.Add(data);//当有客户端接上,先实例化Data类,即接收,发送消息的类,再把类添加到集合中

//tcpClients.Add(tcpClient);

}

Thread.Sleep(100);//线程休眠0.1秒

}

}

catch (Exception e)

{

Console.WriteLine(e);//抛出异常,打印输出

}

}

//获取本地json文件

string GetData()

{

string filePath = AppDomain.CurrentDomain.BaseDirectory + @"/Users.json";

if (!File.Exists(filePath))

{

return null;

}

return File.ReadAllText(filePath);

}

string GetDataGoods()

{

string filePath = AppDomain.CurrentDomain.BaseDirectory + @"/Goods.json";

if (!File.Exists(filePath))

{

return null;

}

return File.ReadAllText(filePath);

}

string GetDataStores()

{

string filePath = AppDomain.CurrentDomain.BaseDirectory + @"/Stores.json";

if (!File.Exists(filePath))

{

return null;

}

return File.ReadAllText(filePath);

}

}

}

Data类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net.Sockets;

using System.Net;

using System.Threading;

using LitJson;

using System.IO;

namespace Package

{

//声明两个最基本的类,Request和Respones,所有与客户端数据的交互都是通过这两个类

public class Request

{

public string Type;

public string Data;

public int Code;

}

public class Respones

{

public string Type;

public string Data;

}

//一个有关于用户的模型

public class UserModel

{

public string Name;//名字

public string PassWord;//密码

public int HP;//血量

public int Attack;//攻击力

public int Speed;//速度

public int[] Goods;//背包不同药品的数量的数组

}

//登录请求

public class login

{

public string Name;

public string Password;

}

//药品模型

public class Goods

{

public string Name;

public int Id;

public string Nature;

public int Value;

public string Icon;

public string Des;

}

//商店商品模型

public class Stores

{

public string Name;

public int Id;

public string Nature;

public int Value;

public string Icon;

public string Des;

}

class Data

{

public TcpClient tcpClient;

public Server server;

public NetworkStream stream;

public Thread thread;

public Data(TcpClient _tcpClient,Server _server)

{

tcpClient = _tcpClient;

server = _server;

thread = new Thread(ReceMsg);//分线程

thread.Start();

}

//接收消息,先接受消息,对消息进行一定的处理后,再调用发送消息的方法

void ReceMsg()

{

try

{

stream = tcpClient.GetStream();

byte[] ReceBuffer = new byte[7000];

while (tcpClient.Connected)

{

int length = stream.Read(ReceBuffer, 0, ReceBuffer.Length);

string str = Encoding.UTF8.GetString(ReceBuffer, 0, length);

Respones info = JsonMapper.ToObject(str);//接受到的消息都转化为Respones 类

Midtranslate(info);

}

}

catch (Exception e)

{

Console.WriteLine(e);

Stop();

}

}

//处理接收到的消息

void Midtranslate(Respones res)

{

Request req = new Request();//定义发送消息的类,实例化内容

req.Type = res.Type;

switch (res.Type)

{

case "Rigister"://接收到注册请求

bool isseek = false;

//接收到客户端传来的内容,先转化为Respones 类,再把Respones 中的Data转化为UserModel 进行处理

//在这里UserModel 是用户的基本信息,把注册成功的用户存储到服务器中.

UserModel model = JsonMapper.ToObject(res.Data);

for (int i = 0; i

{

if (model.Name == server.users[i].Name)

{

req.Data = "账户已存在!";

isseek = true;

break;

}

}

if (isseek == true)

{

req.Code = 0;

}

else

{

req.Data = "注册成功";

req.Code = 1;

server.users.Add(model);//用户信息存储到集合中

server.users.Sort(delegate (UserModel x, UserModel y)//根据战斗力排序

{

return y.Attack.CompareTo(x.Attack);

});

SaveDataUser(JsonMapper.ToJson(server.users));//服务器把用户信息的集合存储到本地

}

sendMsg(req);//发送消息

break;

case "Login":

Console.WriteLine("login接收");

bool isexist = false;

login user1 = JsonMapper.ToObject(res.Data);

for (int i = 0; i

{

if (user1.Name == server.users[i].Name&& user1.Password == server.users[i].PassWord)

{

isexist = true;

req.Data = JsonMapper.ToJson(server.users[i]);

req.Code = 1;

break;

}

}

if (isexist == false)

{

req.Data = "用户名不存在!";

req.Code = 0;

}

sendMsg(req);

break;

case "Goods":

req.Data = JsonMapper.ToJson(server.goods);

req.Code = 1;

sendMsg(req);

break;

case "Stores":

req.Data = JsonMapper.ToJson(server.stores);

req.Code = 1;

sendMsg(req);

break;

case "Ranking":

req.Data = JsonMapper.ToJson(server.users);

req.Code = 1;

sendMsg(req);

break;

case "Save":

bool isrepetition = false;

UserModel user2 = JsonMapper.ToObject(res.Data);

for (int i = 0; i

{

if (server.users[i].Name == user2.Name)

{

server.users[i] = user2;

req.Code = 1;

res.Data = "";

isrepetition = true;

break;

}

}

if (isrepetition == false)

{

req.Code = 0;

res.Data = "";

}

SaveDataUser(JsonMapper.ToJson(server.users));

sendMsg(req);

break;

}

}

void Stop()

{

Console.WriteLine(tcpClient.Client.RemoteEndPoint + "退出");

tcpClient.Client.Close();

thread.Interrupt();

}

//发送消息

void sendMsg(Request req)

{

try

{

byte[] SendBuffer = Encoding.UTF8.GetBytes(JsonMapper.ToJson(req));

stream.Write(SendBuffer, 0, SendBuffer.Length);

}

catch (Exception e)

{

Console.WriteLine(e);

Stop();

}

}

//保存至本地的方法

void SaveDataUser(string data)

{

string filePath = AppDomain.CurrentDomain.BaseDirectory + @"/Users.json";

File.WriteAllText(filePath, data);

}

}

}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180531G0M9MF00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券