C# Winform 實(shí)現(xiàn)TCP發(fā)消息
更新時(shí)間:2021年03月17日 09:44:56 作者:小草上飛飛
這篇文章主要介紹了C# Winform 實(shí)現(xiàn)TCP發(fā)消息的示例,幫助大家更好的理解和學(xué)習(xí)使用c#技術(shù),感興趣的朋友可以了解下
服務(wù)端:
窗體

代碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SocketStudy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 負(fù)責(zé)通信的socket
/// </summary>
Socket socketSend;
/// <summary>
/// 負(fù)責(zé)監(jiān)聽Socket
/// </summary>
Socket socket;
/// <summary>
/// 存放連接的socket
/// </summary>
Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();
/// <summary>
/// 開始監(jiān)聽
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//創(chuàng)建監(jiān)聽的socket,
//SocketType.Stream 流式對(duì)應(yīng)tcp協(xié)議
//Dgram,數(shù)據(jù)報(bào)對(duì)應(yīng)UDP協(xié)議
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//創(chuàng)建IP地址和端口號(hào)
IPAddress ip = IPAddress.Any;//IPAddress.Parse(textServerIP.Text);
int port = Convert.ToInt32(textServerPort.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//讓負(fù)責(zé)監(jiān)聽的Socket綁定ip和端口號(hào)
socket.Bind(iPEndPoint);
ShowLog("監(jiān)聽成功!" + ip + "\t" + port);//打印日志
//設(shè)置監(jiān)聽隊(duì)列
socket.Listen(10);//一段時(shí)間內(nèi)可以連接到的服務(wù)器的最大數(shù)量
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socket);
}
/// <summary>
/// 使用線程來(lái)接收數(shù)據(jù)
/// </summary>
/// <param name="o"></param>
private void Listen(object o)
{
Socket socket = o as Socket;
while(true){
//負(fù)責(zé)監(jiān)聽的socket是用來(lái)接收客戶端連接
//創(chuàng)建負(fù)責(zé)通信的socket
socketSend = socket.Accept();
dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowLog(socketSend.RemoteEndPoint.ToString() + "已連接");
//開啟新線程,接收客戶端發(fā)來(lái)的信息
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start(socketSend);
}
}
//服務(wù)器接收客戶端傳來(lái)的消息
private void receive(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
//客戶端連接成功后,服務(wù)器接收客戶端發(fā)來(lái)的消息
byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
//接收到的有效字節(jié)數(shù)
int length = socketSend.Receive(buffer);
if (length == 0)
{
ShowLog(socketSend.RemoteEndPoint.ToString() + "下線了。");
dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
dictionary[socketSend.RemoteEndPoint.ToString()].Close();
break;
}
string str = Encoding.ASCII.GetString(buffer, 0, length);
ShowLog(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
/// <summary>
/// 日志打印
/// </summary>
/// <param name="str"></param>
private void ShowLog(string str)
{
textLog.AppendText(str + "\r\n");
}
private void Form1_Load(object sender, EventArgs e)
{
//取消對(duì)跨線程調(diào)用而產(chǎn)生的錯(cuò)誤
Control.CheckForIllegalCrossThreadCalls = false;
}
private void sendMsgBtn_Click(object sender, EventArgs e)
{
string txt = textMsg.Text;
byte[] buffer = Encoding.UTF8.GetBytes(txt);
List<byte> list = new List<byte>();
list.Add(0); // 0 為 發(fā)消息
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
//socketSend.Send(buffer);
string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
Socket socketsend=dictionary[ip];
socketsend.Send(newBuffer);
}
private void selectBtn_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.InitialDirectory=@"D:";
fileDialog.Title="選擇文件";
fileDialog.Filter = "所有文件|*.*";
fileDialog.ShowDialog();
pathTxt.Text = fileDialog.FileName;
}
/// <summary>
/// 發(fā)文件,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendFileBtn_Click(object sender, EventArgs e)
{
string path = pathTxt.Text;
FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read);
byte[] buffer = new byte[1024*1024*3];
buffer[0] = 1;// 1 為發(fā)文件的標(biāo)志位
int length = fileStream.Read(buffer, 1, buffer.Length-1);
fileStream.Close();
string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
Socket socketsend = dictionary[ip];
socketsend.Send(buffer,0, length+1, SocketFlags.None);
}
/// <summary>
/// 抖一抖
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void shockBtn_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1];
buffer[0] = 2;// 2 為抖一抖
string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
Socket socketsend = dictionary[ip];
socketsend.Send(buffer);
}
/// <summary>
/// 關(guān)閉前關(guān)閉socket
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
}
catch
{
socket.Close();
}
}
}
}
客戶端:
窗體

代碼
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socket;<br> //連接
private void connectBtn_Click(object sender, EventArgs e)
{
try
{
//創(chuàng)建負(fù)責(zé)通信的socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//地址、端口
IPAddress ip = IPAddress.Parse(ipText.Text);
int serverPort = Convert.ToInt32(portText.Text);
IPEndPoint port = new IPEndPoint(ip, serverPort);
//連接到服務(wù)器
socket.Connect(port);
ShowLog("已連接");
//啟動(dòng)接收數(shù)據(jù)線程
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
}
catch { }
}<br> //日志
private void ShowLog(string str)
{
textLog.AppendText(str + "\r\n");
}
/// <summary>
/// 發(fā)消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendMsgBtn_Click(object sender, EventArgs e)
{
try
{
string txt = sendMsg.Text;
byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii編碼
socket.Send(buffer);
}
catch { }
}
<br> //接收消息<br>
private void receive()
{
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0)
{
break;
}
if (buffer[0] == 0)
{
string txt = Encoding.UTF8.GetString(buffer, 1, length-1);
ShowLog(socket.RemoteEndPoint + ":\r\t" + txt);
}else if (buffer[0] == 1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = @"E:\";
saveFileDialog.Title = "餓了吃什么";
saveFileDialog.Filter = "所有文件 | *.*";
saveFileDialog.ShowDialog(this);
string path = saveFileDialog.FileName;
FileStream fileStreamWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fileStreamWrite.Write(buffer,1,length-1);
fileStreamWrite.Close();
MessageBox.Show("保存成功");
}else if (buffer[0] == 2)
{
ZD();
}
}
catch { }
}
}
//震動(dòng)
private void ZD()
{
for(int i=0;i<20;i++){
if (i%2==0)
{
this.Location = new System.Drawing.Point(500, 500);
}
else
{
this.Location = new System.Drawing.Point(530, 530);
}
Thread.Sleep(20);
}
}
//取消跨線程檢查
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
//關(guān)閉前關(guān)掉socket
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
socket.Disconnect(false);
socket.Close();
}
//斷開連接
private void button1_Click(object sender, EventArgs e)
{
if (socket !=null)
{
socket.Disconnect(false);
}
}
}
}
運(yùn)行結(jié)果:

以上就是C# Winform 實(shí)現(xiàn)TCP發(fā)消息的詳細(xì)內(nèi)容,更多關(guān)于c# 實(shí)現(xiàn)TCP發(fā)消息的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Visual Studio連接unity編輯器的實(shí)現(xiàn)步驟
unity編輯器中打開C#腳本的時(shí)候發(fā)現(xiàn)Visual Studio沒有連接unity編輯器,本文主要介紹了Visual Studio連接unity編輯器的實(shí)現(xiàn)步驟,感興趣的可以了解一下2023-11-11
C#實(shí)現(xiàn)基于鏈表的內(nèi)存記事本實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)基于鏈表的內(nèi)存記事本,實(shí)例分析了C#基于鏈表實(shí)現(xiàn)的記事本功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
C#?winform實(shí)現(xiàn)多語(yǔ)言切換功能
這篇文章主要為大家詳細(xì)介紹了如何使用C#?winform實(shí)現(xiàn)多語(yǔ)言切換功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解下2024-02-02
C#使用正則表達(dá)式隱藏手機(jī)號(hào)中間四位為*
這篇文章主要介紹了C#使用正則表達(dá)式隱藏手機(jī)號(hào)中間四位為*的相關(guān)資料,需要的朋友可以參考下2017-06-06
C#實(shí)現(xiàn)FTP文件下載及超時(shí)控制詳解
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)FTP文件下載及超時(shí)控制的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03

