Socket网络编程(winform)

【服务器】

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.IO;
  7 using System.Linq;
  8 using System.Net;
  9 using System.Net.Sockets;
 10 using System.Text;
 11 using System.Threading;
 12 using System.Windows.Forms;
 13 
 14 namespace SocketDemo
 15 {
 16     public partial class Server : Form
 17     {
 18         private Socket socketSend;
 19 
 20         public Server()
 21         {
 22             InitializeComponent();
 23 
 24         }
 25         private void Form1_Load(object sender, EventArgs e)
 26         {
 27             Control.CheckForIllegalCrossThreadCalls = false;
 28             this.filePath.ReadOnly = true;
 29         }
 30 
 31         private void button1_Click(object sender, EventArgs e)
 32         {
 33             try
 34             {
 35                 //当点击开始监听时,在服务器端创建一个负责监听的ip地址和端口号
 36                 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 37                 IPAddress ip = IPAddress.Any;
 38                 //创建一个端口号
 39                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.portNum.Text));
 40                 //创建监听
 41                 socketWatch.Bind(point);
 42                 ShowMessage("监听成功!");
 43                 socketWatch.Listen(10);
 44                 //等待客户端的链接,并且创建一个负责通信的socket
 45                 Thread thread = new Thread(Listen);
 46                 thread.IsBackground = true;
 47                 thread.Start(socketWatch);
 48             }
 49             catch (Exception)
 50             {
 51             }
 52         }
 53 
 54         Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
 55 
 56 
 57         /// <summary>
 58         /// 等待客户端链接,创建与之通信的scoket
 59         /// </summary>
 60         private void Listen(object o)
 61         {
 62             Socket socketWatch = o as Socket;
 63             while (true)
 64             {
 65                 try
 66                 {
 67                     //等待客户端的连接
 68                     socketSend = socketWatch.Accept();
 69                     //将连接过来的客户端存储至Dictionary和下拉框中,以便区分是哪个客户端
 70                     dic.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
 71                     //将ip和端口号存入下拉框中
 72                     dropList.Items.Add(socketSend.RemoteEndPoint.ToString());
 73                     ShowMessage($"{socketSend.RemoteEndPoint.ToString()}:连接成功!");
 74                     //另外再开一个线程不停地接收客户端发来的消息
 75                     Thread thread = new Thread(Receive);
 76                     thread.IsBackground = true;
 77                     thread.Start(socketSend);
 78                 }
 79                 catch (Exception)
 80                 {
 81                 }
 82             }
 83         }
 84 
 85         /// <summary>
 86         /// 服务器不停地接收客户端发来的消息
 87         /// </summary>
 88         /// <param name="obj"></param>
 89         private void Receive(object obj)
 90         {
 91             Socket socketSend = obj as Socket;
 92             while (true)
 93             {
 94                 try
 95                 {
 96                     //服务器应该接收客户端发来的消息
 97                     byte[] buffer = new byte[1024 * 1024];
 98                     //实际接收的有效字节数
 99                     int num = socketSend.Receive(buffer);
100                     //判断接收的字节是否为0,如果为0,则表明客户端已经下线
101                     if (num == 0)
102                     {
103                         break;
104                     }
105                     string str = Encoding.UTF8.GetString(buffer, 0, num);
106                     ShowMessage($"{socketSend.RemoteEndPoint}:{str}");
107                 }
108                 catch (Exception)
109                 {
110                 }
111             }
112         }
113         private void ShowMessage(string str)
114         {
115             this.textListen.AppendText($"{str}
");
116         }
117 
118         /// <summary>
119         /// 服务器发送消息给客户端
120         /// </summary>
121         /// <param name="sender"></param>
122         /// <param name="e"></param>
123         private void button2_Click(object sender, EventArgs e)
124         {
125             if (dropList.Text == "---请选择---")
126             {
127                 MessageBox.Show("请先选择您要发送的客户端");
128                 return;
129             }
130             if (this.serverMsg.Text.Trim() == "" && this.filePath.Text.Trim() == "")
131             {
132                 MessageBox.Show("请输入信息或选择文件");
133                 return;
134             }
135             List<byte> list = new List<byte>();
136 
137             if (this.serverMsg.Text.Trim() != "" && this.filePath.Text.Trim() == "")
138             {
139                 byte[] buffer = Encoding.UTF8.GetBytes(this.serverMsg.Text.Trim());
140                 //给发送的内容添加前缀,如果加0,则表示发消息
141                 list.Add(0);
142                 list.AddRange(buffer);
143                 byte[] newBuffer = list.ToArray();
144                 dic[dropList.SelectedItem.ToString().Trim()].Send(newBuffer);
145             }
146             else if (this.filePath.Text.Trim() != "" && this.serverMsg.Text.Trim() == "")
147             {
148                 using (FileStream fs = new FileStream(filePath.Text.Trim(), FileMode.Open, FileAccess.Read))
149                 {
150                     byte[] by = new byte[1024 * 1024 * 20];
151                     int length = fs.Read(by, 0, by.Length);
152                     //给发送的内容添加前缀,如果加1,则表示发文件
153                     list.Add(1);
154                     list.AddRange(by);
155                     byte[] newBy = list.ToArray();
156                     dic[dropList.SelectedItem.ToString().Trim()].Send(newBy, 0, length + 1, SocketFlags.None);
157                 }
158             }
159             else
160             {
161                 MessageBox.Show("只能是发送消息或传输文件中的一项");
162             }
163         }
164 
165         /// <summary>
166         /// 打开所需的文件
167         /// </summary>
168         /// <param name="sender"></param>
169         /// <param name="e"></param>
170         private void openFile_Click(object sender, EventArgs e)
171         {
172             OpenFileDialog ofd = new OpenFileDialog();
173             ofd.InitialDirectory = @"C:UsersAdministratorDesktop";
174             ofd.Title = "打开文件";
175             ofd.Filter = "所有文件|*.*";
176             ofd.ShowDialog();
177             this.filePath.Text = ofd.FileName;
178         }
179     }
180 }
View Code

【客户端】

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.IO;
  7 using System.Linq;
  8 using System.Net;
  9 using System.Net.Sockets;
 10 using System.Text;
 11 using System.Threading;
 12 using System.Windows.Forms;
 13 
 14 namespace 客户端
 15 {
 16     public partial class Client : Form
 17     {
 18         public Client()
 19         {
 20             InitializeComponent();
 21         }
 22 
 23         private void Form1_Load(object sender, EventArgs e)
 24         {
 25             Control.CheckForIllegalCrossThreadCalls = false;
 26         }
 27 
 28         Socket socketSend;
 29         private void button1_Click(object sender, EventArgs e)
 30         {
 31             try
 32             {
 33                 //创建一个负责通信的socket
 34                 socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 35                 IPAddress ip = IPAddress.Parse(this.IpMess.Text.Trim());
 36                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.clientPort.Text.Trim()));
 37                 socketSend.Connect(point);
 38                 ShowMess("连接成功!");
 39                 //创建线程接收消息
 40                 Thread th = new Thread(Receive);
 41                 th.IsBackground = true;
 42                 th.Start();
 43             }
 44             catch (Exception)
 45             {
 46                 MessageBox.Show("可能是因为没有启动服务器监听!");
 47             }
 48         }
 49         private void Receive()
 50         {
 51             while (true)
 52             {
 53                 try
 54                 {
 55                     byte[] buffer = new byte[1024 * 1024 * 10]; //最长10M
 56                     //通过字节二进制来接收消息,获取字节长度
 57                     int length = socketSend.Receive(buffer);
 58                     if (length == 0)
 59                     {
 60                         break;
 61                     }
 62                     //如果为0接收消息
 63                     if (buffer[0]==0)
 64                     {
 65                         //去掉前缀
 66                         string str = Encoding.UTF8.GetString(buffer, 1, length-1);
 67                         ShowMess(socketSend.RemoteEndPoint + "" + str);
 68                     }
 69                     //如果为1接收文件
 70                     else if (buffer[0]==1)
 71                     {
 72                         //保存文件
 73                         SaveFileDialog sfd = new SaveFileDialog();
 74                         sfd.InitialDirectory = @"C:UsersAdministratorDesktop";
 75                         sfd.Title = "选择文件";
 76                         sfd.Filter = "所有文件|*.*";
 77                         //弹出对话窗
 78                         sfd.ShowDialog(this);
 79                         using (var fs=new FileStream(sfd.FileName,FileMode.OpenOrCreate,FileAccess.Write))
 80                         {
 81                             fs.Write(buffer, 1, length - 1);
 82                         }
 83                         MessageBox.Show("保存成功");
 84                     } 
 85                 }
 86                 catch (Exception)
 87                 { 
 88                 }
 89             }
 90         }
 91         private void ShowMess(string str)
 92         {
 93             this.clientMess.AppendText($"{str}
");
 94         }
 95 
 96         private void clientMess_TextChanged(object sender, EventArgs e)
 97         {
 98 
 99         }
100 
101         /// <summary>
102         /// 客户端给服务器发送消息
103         /// </summary>
104         /// <param name="sender"></param>
105         /// <param name="e"></param>
106         private void sendBtn_Click(object sender, EventArgs e)
107         {
108             byte[] buffer = Encoding.UTF8.GetBytes(this.sendMsg.Text.Trim());
109             socketSend.Send(buffer);
110         }
111     }
112 }
View Code
世界上最可怕事情是比我们优秀的人比我们还努力
原文地址:https://www.cnblogs.com/AlexOneBlogs/p/7282013.html