Socket
window下的的tcp通信,有改动
服务端:
public static class SocketServer { private static readonly Logger logger = LogManager.GetLogger("DefaultLog"); /// <summary> /// 打开 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void btnListen_Click() { //ip地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); //端口号 IPEndPoint point = new IPEndPoint(ip, int.Parse("12365")); //使用IPv4地址,流式socket方式,tcp协议传递数据 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建好socket后,必须告诉socket绑定的IP地址和端口号。 //让socket监听point try { //socket监听哪个端口 socket.Bind(point); //同一个时间点过来10个客户端,排队 socket.Listen(10); logger.Debug("服务器开始监听"); Thread thread = new Thread(AcceptInfo); thread.IsBackground = true; thread.Start(socket); } catch (Exception ex) { logger.Debug("ex.Message"); } } //记录通信用的Socket static Dictionary<string, Socket> dic = new Dictionary<string, Socket>(); // private Socket client; static void AcceptInfo(object o) { Socket socket = o as Socket; while (true) { //通信用socket try { //创建通信用的Socket Socket tSocket = socket.Accept(); string point = tSocket.RemoteEndPoint.ToString(); //IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint; //string me = Dns.GetHostName();//得到本机名称 //MessageBox.Show(me); logger.Debug(point + "连接成功!"); //cboIpPort.Items.Add(point); dic.Add(point, tSocket); //接收消息 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(tSocket); } catch (Exception ex) { logger.Debug(ex.Message); break; } } } //接收消息 static void ReceiveMsg(object o) { Socket client = o as Socket; while (true) { //接收客户端发送过来的数据 try { //定义byte数组存放从客户端接收过来的数据 byte[] buffer = new byte[1024 * 1024]; //将接收过来的数据放到buffer中,并返回实际接受数据的长度 int n = client.Receive(buffer); //将字节转换成字符串 string words = Encoding.UTF8.GetString(buffer, 0, n); logger.Debug("接收到访问" + ":" + client.RemoteEndPoint.ToString()); //string jsonText = "{\"Id\":\"海淀\",\"PId\":\"haidian\"}"; var sr = JsonConvert.DeserializeAnonymousType<Resu>(words, new Resu()); //发送 btnSend_Click(client.RemoteEndPoint.ToString(), sr.Id); } catch (Exception ex) { logger.Debug(ex.Message); break; } } } static void ShowMsg(string msg) { //txtLog.AppendText(msg + "\r\n"); } /// <summary> /// 判断缓存中是非存在 /// </summary> /// <param name="id"></param> /// <param name="pid"></param> /// <returns></returns> static bool IsExe(string id,string pid) { try { //读取缓存列 var list = studentlist.Where(x => x.Key == id && x.Value == pid); if (list.Count() > 0) { return true; } else { return false; } } catch (Exception ex) { logger.Debug(ex.Message); return true; } } /// <summary> /// 缓存列 /// </summary> static Dictionary<string, string> studentlist = new Dictionary<string, string>(); /// <summary> /// 发送的信息 /// </summary> /// <param name="id"></param> /// <returns></returns> static Dictionary<string, string> RendMsg(string id) { try { //存储发送信息 Dictionary<string, string> res = new Dictionary<string, string>(); string SelSql = "select s.* from Syncstuinfo as s where s.student_id=" + id; DataTable ResSql = AccessHelper.ExecuteDataSet(SelSql).Tables[0]; if (ResSql != null && ResSql.Rows.Count > 0) { //循环查询数据结果 for (int i = 0; i < ResSql.Rows.Count; i++) { string Id = ResSql.Rows[i][0].ToString(); string PId = ResSql.Rows[i]["rfid"].ToString(); //如果缓存中不存在则加入到缓存和消息中 if (!IsExe(Id, PId)) { res.Add(Id, PId); studentlist.Add(Id, PId); } } return res; } else { logger.Debug("查询未空!"); return new Dictionary<string, string>(); } } catch (Exception ex) { logger.Debug(ex.Message); throw; } } //给客户端发送消息 public static void btnSend_Click(string ip,string id) { try { Dictionary<string, string> re = new Dictionary<string, string>(); //re.Add("wang", "w"); //执行逻辑处理得到信息 re= RendMsg(id); //字典转换成json string val = SocketTool.DictionaryToJson(re); //发送 byte[] buffer = Encoding.UTF8.GetBytes(val); dic[ip].Send(buffer); logger.Debug("发送成功"); // client.Send(buffer); } catch (Exception ex) { logger.Debug(ex.Message); } } } //接收参数预留 public class Resu { public string Id { get; set; } public string PId { get; set; } }
/// <summary>
/// 字典转json字符串
/// </summary>
/// <param name="myDic"></param>
/// <returns></returns>
public static string DictionaryToJson(Dictionary<string, string> myDic)
{
string jsonStr = JsonConvert.SerializeObject(myDic);
return jsonStr;
}
客户端:
public partial class Form2 : Form { public Form2() { InitializeComponent(); } Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private void btnConnection_Click(object sender, EventArgs e) { //连接到的目标IP IPAddress ip = IPAddress.Parse(txtIP.Text); //IPAddress ip = IPAddress.Parse("127.0.0.1"); //IPAddress ip = IPAddress.Any; //连接到目标IP的哪个应用(端口号!) IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text)); //IPEndPoint point = new IPEndPoint(ip, int.Parse("12365")); try { //连接到服务器 client.Connect(point); ShowMsg("连接成功"); ShowMsg("服务器" + client.RemoteEndPoint.ToString()); ShowMsg("客户端:" + client.LocalEndPoint.ToString()); //连接成功后,就可以接收服务器发送的信息了 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(); } catch (Exception ex) { ShowMsg(ex.Message); } } //接收服务器的消息 void ReceiveMsg() { while (true) { try { byte[] buffer = new byte[1024 * 1024]; int n = client.Receive(buffer); string s = Encoding.UTF8.GetString(buffer, 0, n); var DIC = Tool.JsonToDictionary(s); ShowMsg(client.RemoteEndPoint.ToString() + ":" + s); } catch (Exception ex) { ShowMsg(ex.Message); break; } } } void ShowMsg(string msg) { txtInfo.AppendText(msg + "\r\n"); } private void btnSend_Click(object sender, EventArgs e) { //客户端给服务器发消息 if (client != null) { try { ShowMsg(txtMsg.Text); byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text); client.Send(buffer); } catch (Exception ex) { ShowMsg(ex.Message); } } } private void ClientForm_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } }