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. Python自动化测试面试题-接口篇

    目录 Python自动化测试面试题-经验篇 Python自动化测试面试题-用例设计篇 Python自动化测试面试题-Linux篇 Python自动化测试面试题-MySQL篇 Python自动化测试面试 ...

  2. C++五十一篇 -- VS2017开发人员新闻无法联网

    参考链接:https://blog.csdn.net/zz1589275782/article/details/88364983 这几天玩了下以前的电脑,本来想更新一下Visual Studio In ...

  3. edraw mindmaster pro 8.1.0安装破解教程

    Edraw MindMaster Pro 8.1.0是一款思维导图(脑图)设计软件,头脑风暴.思维整理.项目策划.团队协作,多场景提升您的效率,功能齐全,个人觉得比xmind好用上手,文章手把手教你安 ...

  4. (python函数01)enumerate函数

    enumerate函数 enumerate函数示例代码01运行结果01示例代码02运行结果02 enumerate(枚举,列举)是python的内置函数,enumerate的参数为可迭代对象,如字符串 ...

  5. jquery.autocomplete 使用解析

    页面引用 <script type="text/javascript" src="${base}/autocom/jquery-1.8.2.min.js" ...

  6. Tr0ll靶机

    一.主机探测 二.信息收集 进入21端口 发现文件并下载 下载文件 作为字典进行登录爆破 用字典爆破 ssh登录 查找信息   /etc/init.d/ssh start scp root@192.1 ...

  7. ContentObserver 内容观察者作用及特点

    eg: 1.定义Uri public static Uri KEY_BROWSER_URI = Uri.parse("content://com.android.browser.provid ...

  8. Java面向对象06——类与对象小结

    小结  /* 1. 类与对象    类是一个模板:抽象,对象是一个具体的实例 2. 方法    定义.调用 ​ 3. 对应的引用    引用类型: 基本类型(8)    对象是通过引用来操作的:栈-- ...

  9. API文档生成(c# dll)

    一.Sandcastle 这个是c#类库方法根据注释生成帮助文档的工具,我们经常会遇到把DLL或者API提供给别人调用的情况,通过在方法中添加注释,然后再用Sandcastle 来自动生成文档给调用者 ...

  10. Clipboard Manager on Xfce

    Clipman-plugin sudo apt-get install xfce4-clipman-plugin No config function. No hotkey. Very basic f ...