TCP/IP以及Socket聊天室带类库源码分享

最近遇到个设备,需要去和客户的软件做一个网络通信交互,一般的我们的上位机都是作为客户端来和设备通信的,这次要作为服务端来监听客户端,在这个背景下,我查阅了一些大佬们的博客,和一些资料。将这些汇总做了一个简单的服务端监听和客户端的类库,希望对大家有一定的作用,当然更多还是给自己做一个日记。下面是类库和对类库测试的一些全部源代码,有需要的可以我QQ获取源代码(674479991)。

1.通信类库

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCP_DLL
{
public class PSS_Server
{
private Dictionary<string, Socket> cilentList = new Dictionary<string, Socket>();
private Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
private Socket ConnCilent;
/// <summary>
/// 创建服务端
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="Port">端口</param>
public PSS_Server(string ip, int Port)
{
IPAddress _IP = IPAddress.Parse(ip);
IPEndPoint endPoint = new IPEndPoint(_IP, Port);
server.Bind(endPoint);
server.Listen(20);
} /// <summary>
/// 接受客户端的连入请求
/// </summary>
/// <param name="retn"></param>
/// <returns></returns>
public bool Accept(ref string retn)
{
string info = "";
try
{
ConnCilent = server.Accept();//接受一个连入的客户端
if (ConnCilent != null)
{
info = ConnCilent.RemoteEndPoint.ToString();
cilentList.Add(info, ConnCilent);
retn = info + "接入服务成功!";
}
return true;
}
catch (Exception)
{
retn = info + "接入服务失败!";
return false;
}
} /// <summary>
/// 发送消息
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool SendMsg(string str)
{
try
{
foreach (var item in cilentList)
{
byte[] arrMsg = Encoding.UTF8.GetBytes(str);
item.Value.Send(arrMsg);
}
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 接收客户端消息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool Receive(object obj, ref string msg)
{
Socket ConnCilent1 = ConnCilent;
IPEndPoint endPoint = null;
try
{
byte[] arrMsg = new byte[1024 * 1024];
int Len = ConnCilent1.Receive(arrMsg);
if (Len != 0)
{
msg = Encoding.UTF8.GetString(arrMsg, 0, Len);
endPoint = ConnCilent1.RemoteEndPoint as IPEndPoint;
}
return true;
}
catch (Exception)
{
if (endPoint!=null)
{
cilentList.Remove(endPoint.ToString());
}
return false;
}
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
try
{
server.Close();
cilentList.Clear();
}
catch (Exception)
{ }
}
} public class PSS_Cilent
{
private Socket cilent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
/// <summary>
/// 创建客户端
/// </summary>
/// <param name="ip"></param>
/// <param name="Port"></param>
public bool Connect(string ip, int Port)
{
IPAddress _ip = IPAddress.Parse(ip);
IPEndPoint endPoint = new IPEndPoint(_ip, Port);
try
{
cilent.Connect(endPoint);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
try
{
cilent.Close();
}
catch (Exception)
{ }
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public bool ReceiveMsg(ref string msg)
{
Socket _Cilent = cilent;
try
{
//定义客户端收到的信息大小
byte[] arrlist = new byte[1024 * 1024];
//接收到的信息大小
int Len = cilent.Receive(arrlist);
msg = Encoding.UTF8.GetString(arrlist, 0, Len);
return true;
}
catch (Exception)
{
_Cilent.Close();
return false;
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public bool SenMsg(string msg)
{
try
{
byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
cilent.Send(arrmsg);
return true;
}
catch (Exception)
{
return false;
}
}
}
}

2.服务端源代码和界面

using System;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ServerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private TCP_DLL.PSS_Server Server;
private void textBox3_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (Server.SendMsg(textBox3.Text).Equals(false))
{
MessageBox.Show("发送消息失败!!");
return;
}
textBox3.Clear();
}
} private void button1_Click(object sender, EventArgs e)
{
string retn = "";
Server = new TCP_DLL.PSS_Server(textBox1.Text, int.Parse(textBox2.Text));
textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建服务完成,等待接入..." + "\r\n"))); if (Server.Accept(ref retn).Equals(false))
{
MessageBox.Show(retn);
return;
}
textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n"))); Task.Factory.StartNew(() =>
{
while (true)
{
string retn1 = "";
if (Server.Receive(ref retn).Equals(false))
{
MessageBox.Show("接收消息异常!!");
return;
}
textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
}
});
} private void button2_Click(object sender, EventArgs e)
{
Server.Close();
}
}
}

2.客户端界面和源代码

using System;
using System.Threading.Tasks;
using System.Windows.Forms; namespace CilentTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private TCP_DLL.PSS_Cilent Cilent = new TCP_DLL.PSS_Cilent(); private void textBox3_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode==Keys.Enter)
{
if (Cilent.SenMsg(textBox3.Text).Equals(false))
{
MessageBox.Show("发送消息失败!!!");
return;
}
textBox3.Clear();
}
} private void button1_Click(object sender, EventArgs e)
{
if (Cilent.Connect(textBox1.Text,int.Parse(textBox2.Text)).Equals(false))
{
MessageBox.Show("连接失败!!!");
return;
}
textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建连接完成....." + "\r\n")));
Task.Factory.StartNew(() =>
{
while (true)
{
string retn = "";
if (Cilent.ReceiveMsg(ref retn).Equals(false))
{
MessageBox.Show("接收消息异常!!");
return;
}
textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
}
});
} private void button2_Click(object sender, EventArgs e)
{
Cilent.Close();
}
}
}

TCP/IP以及Socket聊天室带类库源码分享的更多相关文章

  1. 基于TCP/IP的局域网聊天室---C语言

    具备注册账号,群聊,查看在线人员信息,私发文件和接收文件功能,因为每个客户端只有一个属于自己的socket,所以无论客户端是发聊天消息还是文件都是通过这一个socket发送, 这也意味着服务器收发任何 ...

  2. Java Socket聊天室编程(二)之利用socket实现单聊聊天室

    这篇文章主要介绍了Java Socket聊天室编程(二)之利用socket实现单聊聊天室的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在上篇文章Java Socket聊天室编程(一)之 ...

  3. Java Socket聊天室编程(一)之利用socket实现聊天之消息推送

    这篇文章主要介绍了Java Socket聊天室编程(一)之利用socket实现聊天之消息推送的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 网上已经有很多利用socket实现聊天的例子了 ...

  4. TCP/IP、SOCKET、HTTP之间的联系与区别

    主要内容: 1.网络的七层协议 2.TCP/IP.SOCKET.HTTP简介 3.TCP连接.HTTP连接.Socket连接的区别 一.网络的七层协议 网络七层由下往上分别为物理层.数据链路层.网络层 ...

  5. ios开发网络知识 TCP,IP,HTTP,SOCKET区别和联系

    TCP,IP,HTTP,SOCKET区别和联系 网络由下往上分为:        对应 物理层-- 数据链路层-- 网络层--                       IP协议 传输层--     ...

  6. Linux内核 TCP/IP、Socket参数调优

    Linux内核 TCP/IP.Socket参数调优 2014-06-06  Harrison....   阅 9611  转 165 转藏到我的图书馆   微信分享:   Doc1: /proc/sy ...

  7. 网络协议HTTP、TCP/IP、Socket

    网络协议HTTP.TCP/IP.Socket 网络七层由下往上分别为物理层.数据链路层.网络层.传输层.会话层.表示层和应用层.  其中物理层.数据链路层和网络层通常被称作媒体层,是网络工程师所研究的 ...

  8. python socket 聊天室

    socket 发送的时候,使用的是全双工的形式,不是半双工的形式.全双工就是类似于电话,可以一直通信.并且,在发送后,如果又接受数据,那么在这个接受到数据之前,整个过程是不会停止的.会进行堵塞,堵塞就 ...

  9. 学习懈怠的时候,可以运行Qt自带的Demo,或者Delphi控件自带的Demo,或者Cantu书带的源码,运行一下Boost的例子(搞C++不学习Boost/Poco/Folly绝对是一大损失,有需要使用库要第一时间想到)(在六大的痛苦经历说明,我的理论性确实不强,更适合做实践)

    这样学还不用动脑子,而且熟悉控件也需要时间,而且慢慢就找到感觉了,就可以精神抖擞的恢复斗志干活了.或者Cantu书带的源码. 并且可以使用Mac SSD运行Qt的Demo,这样运行速度快一点. 此外, ...

随机推荐

  1. Unity3D学习笔记3——Unity Shader的初步使用

    目录 1. 概述 2. 详论 2.1. 创建材质 2.2. 着色器 2.2.1. 名称 2.2.2. 属性 2.2.3. SubShader 2.2.3.1. 标签(Tags) 2.2.3.2. 渲染 ...

  2. ifix vba 读取计算机中的txt文件,截取字符串显示

    利用vba脚本,使用Scripting.FileSystemObject对象可以实现对文本文件的操作,下面以一个朋友的实际例子为例将截获的字符串进行页面显示. Private Sub CommandB ...

  3. spingsecurity 前后端分离跨域,ajax无用户信息

    1.自测时用的postman没有任何问题 2.和前端对接时发现登录不上,ajax Error 出错:{"readyState":0,"responseText" ...

  4. for循环排它算法(经典实用)

    核心代码 let lis = document.querySelectorAll("li"); for(let i = 0; i < lis.length; i ++) { ...

  5. Lateral Movement

    简介 这次去宁夏护网,发现我有的朋友连最基本的横向渗透有些都不晓得,他们问我 我也表达不清楚...,就想着写篇文章总结下吧 (慢慢更..) 可以发我邮箱讨论:muxue@protonmail.com ...

  6. 线性代数期末大总结II

    向量组的线性相关性 向量组及其线性组合: n个有次序的数\(a_1,a_2,\cdots,a_n\)所组成的数组称为n维向量,这n个数称为该向量的n个分量,第i个数\(a_i\)称为第i个分量. 若干 ...

  7. Windows常用命令汇总以及基础知识

    命令部分: dir dir指定要列出的驱动器.目录和/或文件 ,/?显示所有命令 例:dir /b /s /o:n /a:a 表示显示当前路径下的所有文件的绝对路径,包含子文件夹的内容 /b表示去除摘 ...

  8. xml的约束

    一.DTD约束xml 1.约束介绍 由于xml的标签由用户自己定义,因此在开发的时候,每个人都可以根据自己的需求来定义xml标签,这样导致项目中的xml难以维护,因此需要使用一定的规范机制来约束xml ...

  9. 《3D打印与工业制造》—— 读书笔记

    <3D打印与工业制造>-- 读书笔记 原创内容,学习不易,转载请注明出处! 一.读后感-- "WOW" ​ 可以这么说,<3D打印与工业制造>这本书是我第一 ...

  10. 简单实现 nodejs koa2 mysql 增删改查 制作接口

    1.首先 在电脑上安装 nodejs (此处略过) 2.全局安装 koa2 (这里使用的淘宝镜像cnpm,有兴趣的同学可以自行搜索下) cnpm install koa-generator -g 3. ...