服務器端代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace socket通信
{
public partial class SERVER : Form
{
public SERVER()
{
InitializeComponent();
}
Socket socketSend;
private void Form1_Load(object sender, EventArgs e)
{
this.ActiveControl = this.btnListen;
txtaidip.Text = GetIpAdress();
//txtport.Text = "80";
Control.CheckForIllegalCrossThreadCalls = false;
}
//將遠程連接的IP地址和Socket存放到集合中
Dictionary<string, Socket> diSocket = new Dictionary<string, Socket>();
private void button1_Click(object sender, EventArgs e)
{
try
{
//創建一個socket,負責監聽IP地址和端口號
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtaidip.Text.Trim()); //提供一個IP地址
IPEndPoint point = new IPEndPoint(ip, 80); //端口號,其中包括了IP地址
socketWatch.Bind(point); //綁定IP地址和端口
ShowMsg("監聽成功");
socketWatch.Listen(10); //設置監聽隊列,最多允許同時10個連接,(0表示不限制)
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch); //socketWatch是Listen()的參數
}
catch
{
}
}
private void ShowMsg(string str)
{
txtReceMsg.AppendText(str + "\r\n");
}
/// <summary>
/// //獲取本機IP地址
/// </summary>
/// <returns></returns>
private string GetIpAdress()
{
try
{
string HostName = Dns.GetHostName(); //得到主機名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; i < IpEntry.AddressList.Length; i++)
{
//從IP地址列表中篩選出IPv4類型的IP地址
//AddressFamily.InterNetwork表示此IP爲IPv4,
//AddressFamily.InterNetworkV6表示此地址爲IPv6類型
if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
return IpEntry.AddressList[i].ToString();
}
}
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 解決只能連接一個用戶的問題
/// </summary>
private void Listen(Object o)
{
Socket socketWatch = o as Socket;
while (true)
{
try
{
//接下來等待客戶端的連接
socketSend = socketWatch.Accept(); //爲客戶端創建一個負責通信的新的socket並接收來自客戶端的請求
//將新的socket存放進集合中
diSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
//將遠程連接的IP地址和端口號存入下拉框
cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":連接成功"); //192.168.0.103:連接成功
Thread th = new Thread(ReceiveSend);
//開啓一個新線程不停接收來自客戶端的消息
th.IsBackground = true;
th.Start(socketSend);
}
catch
{
}
}
}
/// <summary>
/// 服務器端不停的接收客戶端發送過來的消息
/// </summary>
/// <param name="o"></param>
private void ReceiveSend(Object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
//客戶端連接成功後,服務器應該接受客戶端發出的消息
byte[] buffer = new byte[1024*1024 * 1];
int r = socketSend.Receive(buffer); // 實際接收到的有效字節數
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r); //將字節流轉換爲string【str就是客戶端向服務器發送的字符串】
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str); //遠程客戶端連接:接收客戶端發送的內容
}
catch
{
}
}
}
private void btnSendMsg_Click(object sender, EventArgs e)
{ //將服務器端的信息發送給客戶端
string str = txtSendMsg.Text.Trim();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
//socketSend.Send(buffer);
//獲得用戶在下拉框中選中的IP地址,根據IP地址找到對應的socket,然後發送消息
string ip = cboUsers.SelectedIndex.ToString();
diSocket[ip].Send(buffer);
txtReceMsg.AppendText(GetIpAdress() + ">>" + txtSendMsg.Text.Trim() + "\r\n");
txtSendMsg.Text = ""; //清空文本框
}
//在文本框中輸入信息後按【Enter】鍵,觸發【發送消息】事件
private void txtSendMsg_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
btnSendMsg_Click(sender, e);
}
}
}
}
客戶端代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace socket通信客戶端
{
public partial class CLIENT : Form
{
public CLIENT()
{
InitializeComponent();
}
Socket socketSend;
/// <summary>
/// //獲取本機IP地址
/// </summary>
/// <returns></returns>
private string GetIpAdress()
{
try
{
string HostName = Dns.GetHostName(); //得到主機名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; i < IpEntry.AddressList.Length; i++)
{
//從IP地址列表中篩選出IPv4類型的IP地址
//AddressFamily.InterNetwork表示此IP爲IPv4,
//AddressFamily.InterNetworkV6表示此地址爲IPv6類型
if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
return IpEntry.AddressList[i].ToString();
}
}
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//txtlocalip.Text = GetIpAdress();
//txtport.Text = "8080";
Control.CheckForIllegalCrossThreadCalls = false;
this.ActiveControl = this.btnConnection;
}
private void btnConnection_Click(object sender, EventArgs e)
{
try
{
//創建一個socket用來連接服務器
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtaidip.Text.Trim()); //獲取IP地址
IPEndPoint ipep = new IPEndPoint(ip, Convert.ToInt32(txtport.Text.Trim()));
//獲得要連接的遠程服務器的IP地址和端口號
socketSend.Connect(ipep);
showMSG("連接成功");
//創建一個線程,用來不斷接收服務器端發送的信息
Thread th = new Thread(ReceiveMessage);
th.IsBackground = true; //後臺線程
th.Start(socketSend); //socketSend是Start()的參數
}
catch
{
}
}
private void showMSG(string str)
{
txtReceMsg.AppendText(str + "\r\n");
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
string str = txtSendMsg.Text.Trim();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
txtReceMsg.AppendText(GetIpAdress() + ">>" + txtSendMsg.Text.Trim() + "\r\n");
txtSendMsg.Text = "";
}
private void txtMsg_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
this.btnSendMsg_Click(sender, e);
}
}
/// <summary>
/// 不停地接收服務器端發送來的信息
/// </summary>
/// <param name="o"></param>
private void ReceiveMessage(Object o)
{
Socket socketSend = o as Socket;
try
{
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 1];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);
showMSG(socketSend.RemoteEndPoint.ToString() + ":" + str);
}
}
catch
{
}
}
}
}
原文鏈接:https://www.cnblogs.com/decoct-tea/p/12375172.html