TCP/IP以及Socket聊天室带类库源码分享
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聊天室带类库源码分享的更多相关文章
- 基于TCP/IP的局域网聊天室---C语言
具备注册账号,群聊,查看在线人员信息,私发文件和接收文件功能,因为每个客户端只有一个属于自己的socket,所以无论客户端是发聊天消息还是文件都是通过这一个socket发送, 这也意味着服务器收发任何 ...
- Java Socket聊天室编程(二)之利用socket实现单聊聊天室
这篇文章主要介绍了Java Socket聊天室编程(二)之利用socket实现单聊聊天室的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在上篇文章Java Socket聊天室编程(一)之 ...
- Java Socket聊天室编程(一)之利用socket实现聊天之消息推送
这篇文章主要介绍了Java Socket聊天室编程(一)之利用socket实现聊天之消息推送的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 网上已经有很多利用socket实现聊天的例子了 ...
- TCP/IP、SOCKET、HTTP之间的联系与区别
主要内容: 1.网络的七层协议 2.TCP/IP.SOCKET.HTTP简介 3.TCP连接.HTTP连接.Socket连接的区别 一.网络的七层协议 网络七层由下往上分别为物理层.数据链路层.网络层 ...
- ios开发网络知识 TCP,IP,HTTP,SOCKET区别和联系
TCP,IP,HTTP,SOCKET区别和联系 网络由下往上分为: 对应 物理层-- 数据链路层-- 网络层-- IP协议 传输层-- ...
- Linux内核 TCP/IP、Socket参数调优
Linux内核 TCP/IP.Socket参数调优 2014-06-06 Harrison.... 阅 9611 转 165 转藏到我的图书馆 微信分享: Doc1: /proc/sy ...
- 网络协议HTTP、TCP/IP、Socket
网络协议HTTP.TCP/IP.Socket 网络七层由下往上分别为物理层.数据链路层.网络层.传输层.会话层.表示层和应用层. 其中物理层.数据链路层和网络层通常被称作媒体层,是网络工程师所研究的 ...
- python socket 聊天室
socket 发送的时候,使用的是全双工的形式,不是半双工的形式.全双工就是类似于电话,可以一直通信.并且,在发送后,如果又接受数据,那么在这个接受到数据之前,整个过程是不会停止的.会进行堵塞,堵塞就 ...
- 学习懈怠的时候,可以运行Qt自带的Demo,或者Delphi控件自带的Demo,或者Cantu书带的源码,运行一下Boost的例子(搞C++不学习Boost/Poco/Folly绝对是一大损失,有需要使用库要第一时间想到)(在六大的痛苦经历说明,我的理论性确实不强,更适合做实践)
这样学还不用动脑子,而且熟悉控件也需要时间,而且慢慢就找到感觉了,就可以精神抖擞的恢复斗志干活了.或者Cantu书带的源码. 并且可以使用Mac SSD运行Qt的Demo,这样运行速度快一点. 此外, ...
随机推荐
- webpack 命令行报错“webpack” 不是内部或外部命令的解决方法
1. NodeJS安装,笔者安装在D盘.安装目录中有两个文件夹node_cache,node_global如下: 2. 配置 npm安装路径,输入如下命令: npm config set prefix ...
- spring.jpa.open-view问题
由ReentrantLock和JPA(spring.jpa.open-in-view)导致的死锁问题原因分析. 问题 在压测过程中,发现服务经过一段时间压测之后出现无响应,且无法自动恢复. 分析 从上 ...
- 基于arduino UNO R3+ESP8266控制LED灯的开关(无USB转TTL工具实现)
最近由于项目要求,需要开发物联网云平台,而本人对硬件和通信技术一窍不通,故而选择arduino这一简单单片机来实现学习掌握基础的硬件和通信技术. 下面就是本人通过查阅大佬资料做的一个整合版本的通过手机 ...
- java基于mongodb实现分布式锁
原理 通过线程安全findAndModify 实现锁 实现 定义锁存储对象: /** * mongodb 分布式锁 */ @Data @NoArgsConstructor @AllArgsConstr ...
- 嵌套div的onClick事件问题
嵌套div的onClick事件问题我在下面的代码中的外层div中加了onClick事件,这样当鼠标点击这个div的时候就会跳转了.但是我在图片上加了一些其他效果,所以当鼠标点击中间的img时不能触发跳 ...
- Rancher监控指标一文干到底
一.工作负载指标 直接截取一个生产环境的rancher的web管理端-工作负载指标模块的图(这里没有汉化,直接英文)如下: 共5个大指标: CPU使用 内存使用 网络包 网络IO 磁盘IO 自学入口: ...
- spingsecurity 前后端分离跨域,ajax无用户信息
1.自测时用的postman没有任何问题 2.和前端对接时发现登录不上,ajax Error 出错:{"readyState":0,"responseText" ...
- 网络安全日记 ① IIS 之web服务器搭建以及dns转发配置
IIS(internet info server)服务器的搭建 创建iis服务 打开光驱 选择网络应用服务 安装iis和ftp(后面有讲) 配置服务 通过管理工具打开iis 2. 此时80端口就已经开 ...
- azure bash: az: command not found
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=dnf
- Java和Groovy脚本互相调用实例
本实例是GODU动态脚本的一个技术简化版,演示了java调groovy,groovy又调java的运行过程. 测试用例: package com.boco.godu.integration; impo ...