.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;
//每次接收發(fā)送的臨時信息
private byte[] sendData;//發(fā)送的信息
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)//一個信息發(fā)送后再接收為一次完成過程
{
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
}
}
使用方法
public static readonly CacheSocket cac=new CacheSocket(2);
cac.Cmd("發(fā)送內容");
相關文章
詳解ASP.NET Core和ASP.NET Framework共享身份驗證
本篇文章主要介紹了詳解ASP.NET Core和ASP.NET Framework共享身份驗證 ,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12.Net Core WebApi部署到Windows服務器上的步驟
這篇文章主要介紹了.Net Core WebApi部署到Windows服務器上的步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03C#中的FileUpload 選擇后的預覽效果具體實現(xiàn)
選擇后的預覽效果實現(xiàn)的方法有很多,在本文為大家介紹下使用C#中的FileUpload是如何實現(xiàn)的,感興趣的朋友不要錯過2013-12-12ASP.NET Core Controller與IOC結合問題整理
在本篇文章里小編給大家整理了一篇關于ASP.NET Core Controller與IOC結合問題整理內容,有需要的朋友們可以學習下。2021-01-01