客户端代码
复制代码 代码如下:
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
}
}
使用方法
复制代码 代码如下:
public static readonly CacheSocket cac=new CacheSocket(2);
cac.Cmd("发送内容");
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]