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