欢迎您访问我爱IT技术网,今天小编为你分享的编程技术是:【.net socket客户端实例代码分享】,下面是详细的讲解!
.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 netID;
// 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.netID=pNetID;
GetConfig();
Connection();
Cmd("netid:" + this.netID);
}
public CacheSocket(int pNetID, string pIP, int pPort)
{
this.ip=pIP;
this.port=pPort;
Connection();
Cmd("netid:" + 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("netid:" + this.netID);
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 !="success")
{
throw new Exception("连接不成功" + s);
}
}
#endregion
}
}
关于.net socket客户端实例代码分享的用户互动如下:
相关问题:
答: >>详细
相关问题:
答: >>详细
相关问题:
答: >>详细
- 【asp】asp.net url重写浅谈-net-url重写
- 【DataSet】DataSet、DataTable、DataRow区别详解
- 【asp】asp.net 动态添加多个用户控件-net-动态添
- 【创建】ASP.NET Web API教程 创建域模型的方法详
- 【asp】asp.net ubb使用代码-net-ubb使用
- 【默认图片】图片不存在使用默认图片代替的实例
- 【asp】asp.net 页面转向 Response.Redirect Ser
- 【页面打印】关于ASP.NET页面打印技术的常用方法
- 【MVC5】MVC 5 第一章 创建MVC 5 web应用程序-net
- 【MVC】一个简单MVC5 + EF6示例分享-EF6实例-MVC5
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
