2021-6-16 TcpIp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace BatteryDetectWorkA
{
class SocketClient
{
byte[] buffer = new byte[2048];
Socket socket;
Thread thread;
string ip, port;
public bool connect(string ip, string port)
{
bool result = true;
try
{
//实例化socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
this.ip = ip; this.port = port;
socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port))); thread = new Thread(StartReceive);
thread.IsBackground = true;
thread.Start(socket);
}
catch (Exception ex)
{
//SetMessage("连接服务器异常:" + ex.Message);
result = false;
}
return result;
} private void StartReceive(object obj)
{
string str;
while (true)
{
Socket receiveSocket = obj as Socket;
try
{
int result = receiveSocket.Receive(buffer);
if (result == 0)
{
break;
}
else
{
str = Encoding.Default.GetString(buffer); } }
catch (Exception ex)
{
//SetMessage("服务器异常:" + ex.Message); }
} } /// <summary>
/// 关闭连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public bool close()
{
bool result = true;
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
socket.Dispose();
thread.Abort();
socket = null;
thread = null;
GC.Collect();
}
catch (Exception ex)
{
result = false;
}
return result;
} public void send(string str)
{
socket.Send(Encoding.Default.GetBytes(str));
} public void sendbytes(byte[] buffer)
{
socket.Send(buffer);
} public bool isConnection()
{ bool blockingState = socket.Blocking;
try
{
if (!socket.Connected)
{
try
{
close();
connect(this.ip, this.port);
}
catch (Exception ex)
{
return false;
}
}
byte[] tmp = new byte[1];
socket.Blocking = false;
socket.Send(tmp, 0, 0);
socket.Blocking = blockingState; // 恢复状态
return true;
}
catch (SocketException e)
{
//try
//{
// // socket.Close();
// socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port)));
//}
//catch(Exception ex) { }
// 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
//if (e.NativeErrorCode.Equals(10035))
return false;
//else
// return true;
}
//finally
//{
// socket.Blocking = blockingState; // 恢复状态
//} } } class SocketServer
{
private static Dictionary<string, Socket> socketList = new Dictionary<string, Socket>();
public SocketServer(string ip, string port)
{
try
{ Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
//绑定ip和端口
socket.Bind(IEP);
//开启监听
socket.Listen(20);
//Logger.WriteLog(ip + ':' + port + "开始监听"); Thread thread = new Thread(new ParameterizedThreadStart(StartServer));
thread.IsBackground = true;
thread.Start(socket); }
catch (Exception ex)
{
// Logger.WriteLog(ex.Message.ToString(), ex); }
} public void StartServer(object obj)
{
string str;
while (true)
{
//等待接收客户端连接 Accept方法返回一个用于和该客户端通信的Socket
Socket recviceSocket = ((Socket)obj).Accept();
//获取客户端ip和端口号
str = recviceSocket.RemoteEndPoint.ToString();
socketList.Add(str, recviceSocket);
//Logger.LogOperate.Info(str + "已连接"); //Accept()执行过后 当前线程会阻塞 只有在有客户端连接时才会继续执行
//创建新线程,监控接收新客户端的请求数据
Thread thread = new Thread(startRecive);
thread.IsBackground = true;
thread.Start(recviceSocket);
}
} public void startRecive(object obj)
{ while (true)
{
try
{
byte[] buffer = new byte[2048];
int count = ((Socket)obj).Receive(buffer);
if (count == 0) break;
string str = Encoding.Default.GetString(buffer, 0, count);
string ip = ((Socket)obj).RemoteEndPoint.ToString(); }
catch (Exception ex)
{
// Logger.WriteLog(ex.Message.ToString(), ex); }
}
}
private void send2Client(string ip, string str)
{
byte[] bytes = new byte[2048];
bytes = Encoding.Default.GetBytes(str);
if (socketList.ContainsKey(ip))
{
Logger.QuiesceThread(new Action(() => {
try
{
socketList[ip].Send(bytes);
}
catch (Exception ex)
{ }
}));
} } } public class TcpClient
{ Socket m_client; byte[] buffer = new byte[3072 * 2048];
bool isOpen = false;
bool hasClient = false; bool check_client()
{
try
{
if (m_client == null)
return false; bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;
return isConnect;
}
catch
{
return false;
}
} void AcceptCallBack(IAsyncResult ar)
{
try
{
if (check_client())
{
m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);
hasClient = true;
while (hasClient)
{
Thread.Sleep(500);
if (!check_client())
{
break;
}
}
hasClient = false;
Logger.LogApp.Info("监听到Socket断线");
}
if (isOpen)
Open();
}
catch
{
}
}
void ReceiveCallBack(IAsyncResult ar)
{
try
{
var client = ar.AsyncState as Socket;
int length = client.EndReceive(ar);
if (length > 0)
OnDataRecive?.Invoke(buffer.Take(length).ToArray()); //接收一下个信息
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client);
}
catch (Exception ex) { }
} public event Action<byte[]> OnDataRecive;
string m_ip;
int m_port;
public void Open(string ip, int port)
{
//
Close(); //
IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);
m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_client.BeginConnect(serverip, AcceptCallBack, m_client); //
isOpen = true;
m_ip = ip;
m_port = port;
}
public void Open()
{
Open(m_ip, m_port);
}
public void Close()
{
//
if (m_client != null)
{
if (m_client.Connected)
m_client.Shutdown(SocketShutdown.Both);
m_client.Close();
m_client = null;
} //
hasClient = false;
isOpen = false;
}
public bool IsOpen()
{
return isOpen;
}
public bool IsConnected()
{
return hasClient;
} public void Send(byte[] data)
{
if (hasClient)
{
m_client.Send(data);
}
} public void Send(string str)
{
if (hasClient)
{
m_client.Send(Encoding.Default.GetBytes(str));
Logger.LogApp.Info("A工位通过Socket发送" + str.ToString());
}
else
{
Logger.LogApp.Info("Socket断线,数据未发送,数据为" + str.ToString());
}
} } class TcpServer
{ Socket m_server;
Socket m_client; byte[] buffer = new byte[1024];
bool isOpen = false;
bool hasClient = false; bool check_client()
{
try
{
if (m_client == null)
return false; bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;
return isConnect;
}
catch
{
return false;
}
} void AcceptCallBack(IAsyncResult ar)
{
try
{
var server = ar.AsyncState as Socket;
var client = server.EndAccept(ar);
m_client = client;
m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client); hasClient = true;
while (true)
{
Thread.Sleep(100);
if (!check_client())
{
if (m_client.Connected)
m_client.Shutdown(SocketShutdown.Both);
m_client.Close();
m_client = null;
break;
}
}
hasClient = false; if (m_server != null)
{
m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);
}
}
catch { }
}
void ReceiveCallBack(IAsyncResult ar)
{
try
{
var client = ar.AsyncState as Socket;
int length = client.EndReceive(ar);
OnDataRecive?.Invoke(buffer.Take(length).ToArray()); //接收一下个信息
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client);
}
catch { }
} public event Action<byte[]> OnDataRecive; public void Open(string ip, int port)
{ //
Close(); //
IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);
m_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_server.Bind(serverip);
m_server.Listen(0);
m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server); //
isOpen = true;
}
public void Close()
{ //
hasClient = false;
isOpen = false; //
if (m_server != null)
{
if (m_server.Connected)
m_server.Shutdown(SocketShutdown.Both);
m_server.Close();
m_server = null;
} //
if (m_client != null)
{
if (m_client.Connected)
m_client.Shutdown(SocketShutdown.Both);
m_client.Close();
m_client = null;
} }
public bool IsOpen()
{
return isOpen;
}
public bool IsConnected()
{
return hasClient;
} public void Send(byte[] data)
{
if (hasClient)
{
m_client.Send(data);
}
} } }
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Net;using System.Threading;
namespace BatteryDetectWorkA{ class SocketClient { byte[] buffer = new byte[2048]; Socket socket; Thread thread; string ip, port; public bool connect(string ip, string port) { bool result = true; try { //实例化socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //连接服务器 this.ip = ip; this.port = port; socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port)));
thread = new Thread(StartReceive); thread.IsBackground = true; thread.Start(socket); } catch (Exception ex) { //SetMessage("连接服务器异常:" + ex.Message); result = false; } return result; }
private void StartReceive(object obj) { string str; while (true) { Socket receiveSocket = obj as Socket; try { int result = receiveSocket.Receive(buffer); if (result == 0) { break; } else { str = Encoding.Default.GetString(buffer);
}
} catch (Exception ex) { //SetMessage("服务器异常:" + ex.Message);
} }
}
/// <summary> /// 关闭连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public bool close() { bool result = true; try { socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); thread.Abort(); socket = null; thread = null; GC.Collect(); } catch (Exception ex) { result = false; } return result; }
public void send(string str) { socket.Send(Encoding.Default.GetBytes(str)); }
public void sendbytes(byte[] buffer) { socket.Send(buffer); }
public bool isConnection() {
bool blockingState = socket.Blocking; try { if (!socket.Connected) { try { close(); connect(this.ip, this.port); } catch (Exception ex) { return false; } } byte[] tmp = new byte[1]; socket.Blocking = false; socket.Send(tmp, 0, 0); socket.Blocking = blockingState; // 恢复状态 return true; } catch (SocketException e) { //try //{ // // socket.Close(); // socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port))); //} //catch(Exception ex) { } // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的 //if (e.NativeErrorCode.Equals(10035)) return false; //else // return true; } //finally //{ // socket.Blocking = blockingState; // 恢复状态 //}
}
}
class SocketServer { private static Dictionary<string, Socket> socketList = new Dictionary<string, Socket>(); public SocketServer(string ip, string port) { try {
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)); //绑定ip和端口 socket.Bind(IEP); //开启监听 socket.Listen(20); //Logger.WriteLog(ip + ':' + port + "开始监听");
Thread thread = new Thread(new ParameterizedThreadStart(StartServer)); thread.IsBackground = true; thread.Start(socket);
} catch (Exception ex) { // Logger.WriteLog(ex.Message.ToString(), ex);
} }
public void StartServer(object obj) { string str; while (true) { //等待接收客户端连接 Accept方法返回一个用于和该客户端通信的Socket Socket recviceSocket = ((Socket)obj).Accept(); //获取客户端ip和端口号 str = recviceSocket.RemoteEndPoint.ToString(); socketList.Add(str, recviceSocket); //Logger.LogOperate.Info(str + "已连接");
//Accept()执行过后 当前线程会阻塞 只有在有客户端连接时才会继续执行 //创建新线程,监控接收新客户端的请求数据 Thread thread = new Thread(startRecive); thread.IsBackground = true; thread.Start(recviceSocket); } }
public void startRecive(object obj) {
while (true) { try { byte[] buffer = new byte[2048]; int count = ((Socket)obj).Receive(buffer); if (count == 0) break; string str = Encoding.Default.GetString(buffer, 0, count); string ip = ((Socket)obj).RemoteEndPoint.ToString();
} catch (Exception ex) { // Logger.WriteLog(ex.Message.ToString(), ex);
} } } private void send2Client(string ip, string str) { byte[] bytes = new byte[2048]; bytes = Encoding.Default.GetBytes(str); if (socketList.ContainsKey(ip)) { Logger.QuiesceThread(new Action(() => { try { socketList[ip].Send(bytes); } catch (Exception ex) { } })); }
}
}
public class TcpClient {
Socket m_client;
byte[] buffer = new byte[3072 * 2048]; bool isOpen = false; bool hasClient = false;
bool check_client() { try { if (m_client == null) return false;
bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected; return isConnect; } catch { return false; } }
void AcceptCallBack(IAsyncResult ar) { try { if (check_client()) { m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client); hasClient = true; while (hasClient) { Thread.Sleep(500); if (!check_client()) { break; } } hasClient = false; Logger.LogApp.Info("监听到Socket断线"); } if (isOpen) Open(); } catch { } } void ReceiveCallBack(IAsyncResult ar) { try { var client = ar.AsyncState as Socket; int length = client.EndReceive(ar); if (length > 0) OnDataRecive?.Invoke(buffer.Take(length).ToArray());
//接收一下个信息 client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } catch (Exception ex) { } }
public event Action<byte[]> OnDataRecive; string m_ip; int m_port; public void Open(string ip, int port) { // Close();
// IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port); m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_client.BeginConnect(serverip, AcceptCallBack, m_client);
// isOpen = true; m_ip = ip; m_port = port; } public void Open() { Open(m_ip, m_port); } public void Close() { // if (m_client != null) { if (m_client.Connected) m_client.Shutdown(SocketShutdown.Both); m_client.Close(); m_client = null; }
// hasClient = false; isOpen = false; } public bool IsOpen() { return isOpen; } public bool IsConnected() { return hasClient; }
public void Send(byte[] data) { if (hasClient) { m_client.Send(data); } }
public void Send(string str) { if (hasClient) { m_client.Send(Encoding.Default.GetBytes(str)); Logger.LogApp.Info("A工位通过Socket发送" + str.ToString()); } else { Logger.LogApp.Info("Socket断线,数据未发送,数据为" + str.ToString()); } }
}
class TcpServer {
Socket m_server; Socket m_client;
byte[] buffer = new byte[1024]; bool isOpen = false; bool hasClient = false;
bool check_client() { try { if (m_client == null) return false;
bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected; return isConnect; } catch { return false; } }
void AcceptCallBack(IAsyncResult ar) { try { var server = ar.AsyncState as Socket; var client = server.EndAccept(ar); m_client = client; m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);
hasClient = true; while (true) { Thread.Sleep(100); if (!check_client()) { if (m_client.Connected) m_client.Shutdown(SocketShutdown.Both); m_client.Close(); m_client = null; break; } } hasClient = false;
if (m_server != null) { m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server); } } catch { } } void ReceiveCallBack(IAsyncResult ar) { try { var client = ar.AsyncState as Socket; int length = client.EndReceive(ar); OnDataRecive?.Invoke(buffer.Take(length).ToArray());
//接收一下个信息 client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } catch { } }
public event Action<byte[]> OnDataRecive;
public void Open(string ip, int port) {
// Close();
// IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port); m_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_server.Bind(serverip); m_server.Listen(0); m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);
// isOpen = true; } public void Close() {
// hasClient = false; isOpen = false;
// if (m_server != null) { if (m_server.Connected) m_server.Shutdown(SocketShutdown.Both); m_server.Close(); m_server = null; }
// if (m_client != null) { if (m_client.Connected) m_client.Shutdown(SocketShutdown.Both); m_client.Close(); m_client = null; }
} public bool IsOpen() { return isOpen; } public bool IsConnected() { return hasClient; }
public void Send(byte[] data) { if (hasClient) { m_client.Send(data); } }
}
}
2021-6-16 TcpIp的更多相关文章
- 2021.12.16 eleveni的刷题记录
2021.12.16 eleveni的刷题记录 1. 数论 https://www.luogu.com.cn/problem/P2532 1.1卡特兰数 https://www.luogu.com.c ...
- 2021.11.16 P2375 [NOI2014] 动物园(EXKMP+差分)
2021.11.16 P2375 [NOI2014] 动物园(EXKMP+差分) https://www.luogu.com.cn/problem/P2375 题意: PS:这道神题的背景让人疑惑,重 ...
- 2021.08.16 P1260 工程规划(差分约束)
2021.08.16 P1260 工程规划(差分约束) 重点: 1.跑最短路是为了满足更多约束条件. P1260 工程规划 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意: 造 ...
- 2021.08.16 P1078 文化之旅(最短路)
2021.08.16 P1078 文化之旅(最短路) 题意: n个地,k个信仰,每个地都有自己的信仰,信仰之间会相互排斥,同信仰之间也会相互排斥,有m条路,问从s到t的最短距离是多少? 有一位使者要游 ...
- 2021.08.16 P1300 城市街道交通费系统(dfs)
2021.08.16 P1300 城市街道交通费系统(dfs) P1300 城市街道交通费系统 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意: 城市街道交费系统最近创立了.一 ...
- 2021.08.16 P1363 幻象迷宫(dfs,我感受到了出题人浓浓的恶意)
2021.08.16 P1363 幻象迷宫(dfs,我感受到了出题人浓浓的恶意) P1363 幻象迷宫 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意: 幻象迷宫可以认为是无限 ...
- Noip模拟78 2021.10.16
这次时间分配还是非常合理的,但可惜的是$T4$没开$\textit{long long}$挂了$20$ 但是$Arbiter$上赏了蒟蒻$20$分,就非常不错~~~ T1 F 直接拿暴力水就可以过,数 ...
- Noip模拟54 2021.9.16
T1 选择 现在发现好多题目都是隐含的状压,不明面给到数据范围里,之凭借一句话 比如这道题就是按照题目里边给的儿子数量不超过$10$做状压,非常邪门 由于数据范围比较小,怎么暴力就怎么来 从叶子节点向 ...
- Noip模拟41 2021.8.16
T1 你相信引力吗 对于区间的大小关系问题,往往使用单调栈来解决 这道题的优弧和劣弧很烦,考虑将其等价的转化 由于所有的合法情况绕过的弧都不会经过最高的冰锥, 又因为环可以任意亲定起点,这样可以直接把 ...
- Noip模拟17 2021.7.16
我愿称这场考试为STL专练 T1 世界线 巧妙使用$bitset$当作vis数组使用,内存不会炸,操作还方便,的确是极好的. 但是这个题如果不开一半的$bitset$是会炸内存的,因为他能开得很大,但 ...
随机推荐
- Java的初始化块
三种初始化数据域的方法: 在构造器中设置值 在声明中赋值 初始化块(initialization block) 初始化块 在一个类的声明中,可以包含多个代码块.只要构造类的对象,这些块就会被执行. c ...
- sqlilabs第一关
首先打开网页,进行注入点的测试 输入?id=1 and 1=1发现1=2的时候没有进行报错,有两种可能,一种是不能注入,第二种是字符型可以通过对字符型里面的''进行闭合,输入'and 1=1--+发现 ...
- 2020-08-22:I/O多路复用中select/poll/epoll的区别?
福哥答案2020-08-22: select,poll,epoll 都是 操作系统实现 IO 多路复用的机制. 我们知道,I/O 多路复用就通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是 ...
- 2021-01-30:redis中,Pipeline有什么好处?
福哥答案2021-01-30:可以将多次 IO 往返的时间缩减为一次,减少多次IO延迟的开销.前提是 pipeline 执行的指令之间没有因果相关性. 多个指令之间没有依赖关系,可以使用 pipeli ...
- 2021-11-02:生命游戏。根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个
2021-11-02:生命游戏.根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机.给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个 ...
- ICLR 2018-A Simple Neural Attentive Meta-Learner
Key 时序卷积+注意力机制(前者从过去的经验中收集信息,而后者则精确定位具体的信息.) 解决的主要问题 手工设计的限制:最近的许多元学习方法都是大量手工设计的,要么使用专门用于特定应用程序的架构,要 ...
- 一文读懂面试官都在问的Fastjson漏洞
Fastjson1.2.24-RCE漏洞 漏洞简介 fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符 ...
- vue 一键导出数据为excel文件并附带样式 十分简单
自入行以来我就一直疑惑一个问题,导出excel为什么总是搞的很复杂,包括网上的教程,屎里淘金,非常耗费精力.今天刚好业务需要,整理一个简单明了的由vue前端导出的版本出来. 开始: #1.添加xlsx ...
- JVM系统参数
JVM(Java虚拟机)是Java程序的运行环境,它可以通过一些系统参数进行配置和优化.以下是一些常用的JVM系统参数: 1. -Xmx: 用于设置JVM堆的最大内存大小.例如,-Xmx1g表示将堆的 ...
- Android APK 文件结构
序言 APK(全称:Android application package,Android应用程序包)是Android操作系统使用的一种应用程序包文件格式,用于分发和安装移动应用及中间件. APK 文 ...