.net socket客户端实例代码分享
客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace W.Common
{
public class CacheSocket
{
public Socket skClient;
public string ip = string.Empty;
public int port = -1;
public int ID;
// public int timeSleep = 1;
//每次接收发送的临时信息
private byte[] sendData;//发送的信息
private byte[] receiveData = new byte[1024];//接收信息
private int receiveN;
private bool isErr = false;
//--------
public CacheSocket(int pNetID)
{
this.ID = pNetID;
GetConfig();
Connection();
Cmd("id:" + this.ID);
}
public CacheSocket(int pNetID, string pIP, int pPort)
{
this.ip = pIP;
this.port = pPort;
Connection();
Cmd("id:" + pNetID);
}
public string Cmd(string key)
{
lock (this)//一个信息发送后再接收为一次完成过程
{
this.sendData = Encoding.UTF8.GetBytes(key);
try
{
this.skClient.Send(this.sendData);
}
catch (Exception ex)
{
isErr = true;
("Send" + ex.Message).WriteLine();
ReSocket(() => { this.skClient.Send(this.sendData); });
}
try
{
this.receiveN = this.skClient.Receive(this.receiveData);
}
catch (Exception ex)
{
isErr = true;
ReSocket(() => { this.receiveN = this.skClient.Receive(this.receiveData); });
("Receive" + ex.Message).WriteLine();
}
return Encoding.UTF8.GetString(this.receiveData, 0, this.receiveN);
}
}
public delegate void ReSocket_D();
private void ReSocket(ReSocket_D d)
{
if (isErr)
{
Connection();
this.sendData = Encoding.UTF8.GetBytes("id:" + this.ID);
this.skClient.Send(this.sendData);
this.receiveN = this.skClient.Receive(this.receiveData);
if (Encoding.UTF8.GetString(this.receiveData, 0, this.receiveN) != "1")
{
}
d();
this.isErr = false;
}
}
#region 获取IP和端口
private void GetConfig()
{
this.ip = "127.0.0.1";
this.port = 1234;
}
#endregion
#region 连接套接字
private void Connection()
{
this.skClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(this.ip), this.port);//服务器的IP和端口
skClient.Connect(ie);
byte[] data = new byte[7];
this.receiveN = this.skClient.Receive(data);
string s = Encoding.UTF8.GetString(data, 0, this.receiveN);
if (s != "suess")
{
throw new Exception("连接不成功" + s);
}
}
#endregion
}
}
使用方法
public static readonly CacheSocket cac=new CacheSocket(2);
cac.Cmd("发送内容");
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指