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();
}
}
}

最新文章

  1. 字符串匹配的KMP算法——Python实现
  2. 详解x86、IA-32、IA-64等CPU系列
  3. MSSQL手札四 MSSQL的函数
  4. iOS 数据类型
  5. 【Cocos2d入门教程七】三分钟看懂Cocos2d坐标系
  6. UIcollectionView的使用(首页的搭建1)
  7. C#核编之一个简单的C#程序
  8. 最好用的css辅助工具——SASS&amp;LESS
  9. Maven 编译错误 Dynamic Web Module 3.0 requires Java 1.6 or newer 解决方案
  10. Mac下安装php5.6/7.1
  11. LeakCanary检测内存泄漏.md
  12. Windows系统版本判定那些事儿
  13. CSS+DIV定位分析(relative,absolute,static,fixed)
  14. qml layout
  15. 第一册:lesson109.
  16. 《重构-改善既有代码的设计》学习笔记----Extract Method(提炼函数)
  17. vue中使用axios最详细教程
  18. Android美丽的对话框项目sweet-alert-dialog
  19. MySQL异步复制-加强版
  20. 《算法》第四章部分程序 part 5

热门文章

  1. python---replace函数
  2. 如何使用Git Flow 进行hotfix
  3. python3实现名片管理系统(文件版)
  4. spring IOC体系图
  5. etcd raft 处理流程图系列2-wal的读写
  6. javaSE面向对象编程
  7. 软件或jar包版本的小知识---Beta版、Final版、Free版等
  8. Grid布局如何设置动画效果
  9. Vue系列-04-项目1
  10. 阿里云云服务器 ECS和云数据库 PolarDB的简单使用