服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# Winform 实现TCP发消息

C# Winform 实现TCP发消息

2022-11-08 12:07小草上飞飞 C#

这篇文章主要介绍了C# Winform 实现TCP发消息的示例,帮助大家更好的理解和学习使用c#技术,感兴趣的朋友可以了解下

服务端:

窗体

C# Winform 实现TCP发消息

代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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>
        /// 负责通信的socket
        /// </summary>
        Socket socketSend;
 
        /// <summary>
        /// 负责监听Socket
        /// </summary>
        Socket socket;
 
        /// <summary>
        /// 存放连接的socket
        /// </summary>
        Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();
 
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //创建监听的socket,
            //SocketType.Stream 流式对应tcp协议
            //Dgram,数据报对应UDP协议
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建IP地址和端口号
            IPAddress ip = IPAddress.Any;//IPAddress.Parse(textServerIP.Text);
            int port = Convert.ToInt32(textServerPort.Text);
            IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
 
            //让负责监听的Socket绑定ip和端口号
            socket.Bind(iPEndPoint);
 
            ShowLog("监听成功!" + ip + "\t" + port);//打印日志
 
            //设置监听队列
            socket.Listen(10);//一段时间内可以连接到的服务器的最大数量
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socket);
        }
 
        /// <summary>
        /// 使用线程来接收数据
        /// </summary>
        /// <param name="o"></param>
        private void Listen(object o)
        {
            Socket socket = o as Socket;
            while(true){
                //负责监听的socket是用来接收客户端连接
                //创建负责通信的socket
                socketSend = socket.Accept();
                dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());
 
                ShowLog(socketSend.RemoteEndPoint.ToString() + "已连接");
 
                //开启新线程,接收客户端发来的信息
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start(socketSend);
            }
        }
 
        //服务器接收客户端传来的消息
        private void receive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    //客户端连接成功后,服务器接收客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
                                                              //接收到的有效字节数
                    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)
        {
            //取消对跨线程调用而产生的错误
            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 为 发消息
            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>
        /// 发文件,
        /// </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 为发文件的标志位
            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>
        /// 关闭前关闭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();
            }
        }
    }
}

客户端:

窗体

C# Winform 实现TCP发消息

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
            {
                //创建负责通信的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);
                //连接到服务器
                socket.Connect(port);
                ShowLog("已连接");
 
                //启动接收数据线程
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start();
            }
            catch { }
        }<br>    //日志
        private void ShowLog(string str)
        {
            textLog.AppendText(str + "\r\n");
        }
 
        /// <summary>
        /// 发消息
        /// </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 { }
            }
        }
      //震动
        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;
        }
    //关闭前关掉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);
            }
        }
    }
}

运行结果:

C# Winform 实现TCP发消息

以上就是C# Winform 实现TCP发消息的详细内容,更多关于c# 实现TCP发消息的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/FlyonGrass/p/14068311.html

延伸 · 阅读

精彩推荐
  • C#Unity实现引导页效果

    Unity实现引导页效果

    这篇文章主要为大家详细介绍了Unity实现引导页效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    贪玩的孩纸时代11342022-09-02
  • C#C#微信开发之微信公众号标签管理功能

    C#微信开发之微信公众号标签管理功能

    这篇文章主要介绍了C#微信开发之微信公众号标签管理功能 的相关资料,需要的朋友可以参考下...

    伍华聪6212021-11-21
  • C#Unity实现通用的信息提示框

    Unity实现通用的信息提示框

    这篇文章主要为大家详细介绍了Unity实现通用的信息提示框,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    xiaochenXIHUA5402022-09-16
  • C#C#byte数组传入C操作方法

    C#byte数组传入C操作方法

    在本篇内容中小编给大家分享了关于C#byte数组传入C操作方法以及相关知识点,需要的朋友们学习下。...

    C#教程网9172022-07-06
  • C#C#使用Object类实现栈的方法详解

    C#使用Object类实现栈的方法详解

    这篇文章主要介绍了C#使用Object类实现栈的方法,详细分析了栈的原理及使用Object类实现栈的相关技巧与注意事项,需要的朋友可以参考下...

    丛晓男6102021-11-29
  • C#深入了解c# 迭代器和列举器

    深入了解c# 迭代器和列举器

    这篇文章主要介绍了c# 迭代器和列举器的相关资料,帮助大家更好的理解和学习C#,感兴趣的朋友可以了解下...

    精致码农 • 王亮11582022-10-07
  • C#详解c# 中的DateTime

    详解c# 中的DateTime

    这篇文章主要介绍了c# 中的DateTime的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    Tiger.wang8262022-09-26
  • C#C# 判断时间段是否相交的实现方法

    C# 判断时间段是否相交的实现方法

    这篇文章主要介绍了C# 判断时间段是否相交的实现方法的相关资料,希望通过本文能帮助到大家,让大家实现这样的功能,需要的朋友可以参考下...

    _iorilan9352022-01-25