socketServer
基于Socket完成服务端的代码编写
代码里面链接提醒,数据接收发送,延迟判断连接成功失败,以下是具体的代码
使用代码时要记得安装JSON库,具体怎么安装的忘了,可以看报错提示安装,即可,有什么问题可以留言,我这继续修改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Reflection;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;
using System.CodeDom.Compiler;
using System.Net.NetworkInformation;
namespace NW_Fk
{
//调用函数前需先调用ConnectPower()和ConnectRefMeter()函数初始化参数。
public class SocketTest
{
public static Socket socket = null;
public static Socket ServerSocket = null;
public static void ThreadSocket()
{
ThreadPool.QueueUserWorkItem(StartSocket);
//启动socket
// 创建线程并启动
//Thread socketThread = new Thread(StartSocket);
//socketThread.Start();
}
public static void StartSocket(object o)
{
//定义需要用到的属性
int RetryDelay = 3000; // 重试延迟(毫秒)
bool isConnected = false;//连接状态
int port = 6788;//定义监听端口号
IPAddress ipAdd = IPAddress.Parse("127.0.0.1");//初始化ip地址
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化socket链接
IPEndPoint point = new IPEndPoint(ipAdd, port);
socket.Bind(point);
}
catch (Exception e1)
{
MessageBox.Show(e1.StackTrace);
}
try
{
while (true)
{
//客户端监听
socket.Listen(10);
//客户端链接
Console.WriteLine("等待客户端连接...");
ServerSocket = socket.Accept();
Thread.Sleep(RetryDelay);// 延迟时间
byte[] resultOk = Encoding.UTF8.GetBytes(ipAdd + ":" + port);
ServerSocket.Send(resultOk);//向socket发送连接成功
Console.WriteLine("连接成功");
// 连接成功
isConnected = true;
//连接完成后将 isConnected 变为true 执行下面方法
while (isConnected == true)
{
try
{
byte[] buffer = new byte[1024];//创建byte数组
int bytesRead = ServerSocket.Receive(buffer);// 接收数据
// 将接收到的字节数组转换为字符串
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
//判断接收数据是否为空 如果为空,则判断当前连接断开
if (receivedData.Length > 0)
{
// 解析JSON字符串
var jsonObject = JObject.Parse(receivedData);
// 获取MethodName
string methodName = jsonObject["MethodName"].ToString();
// 获取JsonDarams中的参数值
JObject jsonParams = (JObject)jsonObject["JsonParams"];
Console.WriteLine(methodName);
// 与电能表检定装置建立连接、初始化
if (methodName == "hello")
{
string hello = "hello";
// 打印执行结果
Console.WriteLine("methodName()--->>> " + methodName);
//定义json嵌套格式
string json = @"
{
""MethodName"": """",
""data"": {
""result"": """"
}
}";
//将嵌套格式转成json对象
JObject jsonObj = JObject.Parse(json);
//定义内层 dataObj 的 results 属性值
JObject dataObj = new JObject(
new JProperty("result", hello)
);
//定义外层json属性值
JObject outObj = new JObject(
new JProperty("MethodName", methodName),
new JProperty("data", dataObj)
);
string Json = outObj.ToString();
Console.WriteLine("result" + Json);
// 发送执行结果到客户端
byte[] resultBytes = Encoding.UTF8.GetBytes(Json);
ServerSocket.Send(resultBytes);
}
}
else
{
Console.WriteLine("重新监听");
isConnected = false;
}
//当上面的方法出现异常后,执行cache方法
}
catch (NullReferenceException e)
{
Console.WriteLine("出现了NullReferenceException" + e.StackTrace);
continue;
}
catch (JsonReaderException e)
{
Console.WriteLine("出现了JsonReaderException" + e.StackTrace);
continue;
}
catch (SocketException)
{
isConnected = false;
Console.WriteLine("出现了SocketException");
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}