C # Socket Programming Sample

Using server-side programming Socket Communications, familiar with the communication process server and client, to achieve the send and receive information, file transfer and vibration function

on the server side to create a Socket, then local ip address and port number of the connection, that is, using Bind method, and then use the listen method to listen.

Accept the connection request client with Accept method, and waits for client connections (in winform, because the Accept method is a blocking method, you must create a thread to perform, to prevent the main form stuck)

client to connect successfully Accept method returns a use Socket to send and receive messages, then we must use the socket communication

to image different functions, such as file transfer, it is necessary to use a certain position in the course of communication of the byte stream sent to store information, which is used their own protocol, in this case, take the first byte of the identification information, transmitting information representative of 0, 1 for file transfer, represents vibration form

server code as follows

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 using System.Windows.Forms;
 10 using System.Net.Sockets;
 11 using System.Net;
 12 using System.Threading;
 13 using System.IO;
 14  
 15 namespace ServerReview
 16 {
 17     public partial class Form1 : Form
 18     {
 19         public Form1()
 20         {
 21             InitializeComponent();
 22         }
 23         private Socket socketSend;
 24         private Socket socketWatch;
 25         private Dictionary<string, Socket> socketClientList = new Dictionary<string, Socket>();
 26         private voidbtnStart_Click ( Object SENDER, EventArgs E)
 27          {
 28              socketWatch = new new the Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 29              the IPAddress IP = IPAddress.Any;
 30              the IPEndPoint IEP = new new the IPEndPoint (IP, Convert.ToInt32 ( txtPort.Text));
 31 is              // socket and the unit address binding 
32              socketWatch.Bind (IEP);
 33 is              ShowMsg ( " listen success " );
 34              // with listen monitor 
35              socketWatch.Listen (10 );
 36              // create a new thread stop accept client requests 
37 [              the Thread Thread = new new the Thread (ServerAccept);
 38 is              thread.IsBackground = to true ;
 39              Thread.Start ();
 40          }
 41 is          Private  void ServerAccept ()
 42 is          {
 43 is              the while ( to true )
 44 is              {
 45                  socketSend = socketWatch.Accept ();
 46 is                  socketClientList.Add (socketSend.RemoteEndPoint.ToString (), socketSend);
47                  cboUsers.Items.Add (socketSend.RemoteEndPoint.ToString ());
 48                  ShowMsg (socketSend.RemoteEndPoint.ToString () + " connection successful " );
 49                  // open new thread stop receiving messages 
50                  the Thread Thread = new new the Thread ( ServerReceive);
 51 is                  thread.IsBackground = to true ;
 52 is                  Thread.Start ();
 53 is              }
 54 is          }
 55          Private  void ServerReceive ()
 56 is          {
 57 is              the while ( to true)
 58             {
 59                 try
 60                 {
 61                     byte[] buffer = new byte[1024 * 1024 * 2];
 62                     int byteNum = socketSend.Receive(buffer);
 63                     if (byteNum == 0)
 64                     {
 65                         break;
 66                     }
 67                     string str = Encoding.UTF8.GetString(buffer, 0, byteNum);
 68                     ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
 69                 }
 70                 catch { }
 71             }
 72         }
 73         private void ShowMsg(string str)
 74         {
 75             txtLog.AppendText(str + "\r\n");
 76         }
 77  
 78         private void Form1_Load(object sender, EventArgs e)
 79         {
 80             Control.CheckForIllegalCrossThreadCalls = false;
 81         }
 82  
 83         private void btnSend_Click(object sender, EventArgs e)
 84         {
 85             string str = txtMsg.Text;
 86             List<byte> list = new List<byte>();
 87             list.Add(0);
 88             byte[] buffer = Encoding.UTF8.GetBytes(str);
 89             list.AddRange(buffer);
 90             byte[] newBuffer = list.ToArray();
 91             string ip = cboUsers.SelectedItem.ToString();
 92             socketClientList[ip].Send(newBuffer);
 93         }
 94  
 95         private void btnSelectFile_Click(object sender, EventArgs e)
 96         {
 97             OpenFileDialog ofd = new OpenFileDialog();
 98             ofd.InitialDirectory = @"D:\";
 99             ofd.Title = "请选择要发送的文件";
100             ofd.Filter = "所有文件|*.*";
101             ofd.ShowDialog();
102             txtFilePath.Text = ofd.FileName;
103         }
104  
105         private void btnSendFile_Click(object sender, EventArgs e)
106         {
107             string path = txtFilePath.Text;
108             using(FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))
109             {
110                 try
111                 {
112                     byte[] buffer = new byte[1024 * 1024 * 5];
113                     int l = fsRead.Read(buffer, 0, buffer.Length);
114                     List<byte> list = new List<byte>();
115                     list.Add(1);
116                     list.AddRange(buffer);
117                     byte[] newBuffer = list.ToArray();
118                     socketClientList[cboUsers.SelectedItem.ToString()].Send(newBuffer,0,l+1,SocketFlags.None);
119                 }
120                 catch { }
121             }
122         }
123  
124         private void btnShake_Click(object sender, EventArgs e)
125         {
126             byte[] buffer = new byte[1];
127             buffer[0] = 2;
128             socketClientList[cboUsers.SelectedItem.ToString()].Send(buffer);
129         }
130     }
131 }

Client code as follows:

 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.Threading.Tasks;
13 using System.Windows.Forms;
14  
15 namespace ClientRevier
16 {
17     public partial class Form1 : Form
18     {
19         public Form1()
20         {
21             InitializeComponent();
22         }
23  
24         private void Form1_Load(object sender, EventArgs e)
25         {
26             Control.CheckForIllegalCrossThreadCalls = false;
27         }
28         private Socket socketClient;
29         Private  void btnStart_Click ( Object SENDER, EventArgs E)
 30          {
 31 is              SocketClient = new new the Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 32              the IPAddress IP = IPAddress.Parse (txtServer.Text);
 33 is              the IPEndPoint IEP = new new the IPEndPoint (IP, Convert.ToInt32 (txtPort.Text));
 34 is              socketClient.Connect (IEP);
 35              ShowMsg ( " connection successful " );
 36              // as to keep accept message, so the while loop, and to accept message At the same time to do other things, put this thread execution 
37             Thread thread = new Thread(ClientRecieve);
38             thread.IsBackground = true;
39             thread.Start();
40         }
41         private void ClientRecieve()
42         {
43             while (true)
44             {
45                 byte[] buffer = new byte[1024 * 1024 * 2];
46                 int byteNum = socketClient.Receive(buffer);
47                 if (byteNum == 0)
48                 {
49                     break;
50                 }
51                 switch (buffer[0])
52                 {
53                     case 0:
54                         string str = Encoding.UTF8.GetString(buffer, 1, byteNum-1);
55                         ShowMsg(socketClient.RemoteEndPoint + ":" + str);
56                         break;
57                     case 1:
58                         SFD = SaveFileDialog new new SaveFileDialog ();
 59                          sfd.InitialDirectory = @ " D \ " ;
 60                          sfd.Title = " Please choose the path needs to be saved " ;
 61                          sfd.Filter = " text file | * .txt | Image Files | * .jpg | All files | * *. " ;
 62 is                          sfd.ShowDialog ( the this );
 63 is                          the using (= the FileStream fsWrite new new the FileStream (sfd.FileName, FileMode.OpenOrCreate, FileAccess.Write))
 64                          {
 65                             fsWrite.Write(buffer, 1, byteNum - 1);
66                             MessageBox.Show("保存成功");
67                         }
68                         break;
69                     case 2:
70                         for(int i = 0; i < 1000; i++)
71                         {
72                             this.Location = new Point(200, 200);
73                             this.Location = new Point(230, 230);
74                         }
75                         break;
76                     default:break;
77                 }
78                 
79             }
80         }
81         private void ShowMsg(string str)
82         {
83             txtLog.AppendText(str + "\r\n");
84         }
85  
86         private void btnSend_Click(object sender, EventArgs e)
87         {
88             string str = txtMsg.Text;
89             byte[] buffer = Encoding.UTF8.GetBytes(str);
90             socketClient.Send(buffer);
91  
92         }
93     }
94 }

 

Guess you like

Origin www.cnblogs.com/SunShineYPH/p/11568678.html