C # Socket network programming,

Source: Internet
Author: User

C # Socket network programming,

I'm a newbie and have never written a blog before. I hope you don't need to spray it,

When writing a Socket, You need to importSystem. Net. SocketNamespace. Using this class, we can directly write the Socket Client and the service program,

Here we only talk about Socket programming under the tpc protocol.

The TCP Socket connection process can be simply divided:①. Server listening ②. client request ③. Establish a connection,

On the server:

(1) declare a Socket (called a listening Socket) Socket serverSocket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );

(2) declare an EndPoint. As mentioned above, the Socket needs to be bound to it for communication. IPEndPoint endPoint = new IPEndPoint (IPAddress. Loopback, 8080 );

(3) set the listener queue serverSocket. Listen (100 );

(4) use the Accept () method to obtain a communication socket (when a client is connected). This method will block the thread and prevent the interface from dying and start a thread, put this Accept () in the thread function.

On the client:

(1) declare a socket and initiate a connection to the server through connect.

(2) Use the Receive method to obtain messages sent from the server (a thread is also enabled here to monitor messages sent by the server in real time through the while LOOP)

Note: Data is transmitted as Byte streams (Byte []). I will use the Encoding. UTF8.GetString () method to obtain the data as a string. Both Send () messages to each other.

We can directly useSocketClass to build a simple Socket Application. directly add the Code. This is the server code ..

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. net; using System. net. sockets; using System. text; using System. threading; using System. threading. tasks; using System. windows. forms; using System. IO; namespace WindowsFormsApplication1 {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button1_Click (object sender, EventArgs e) {Socket s = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); IPAddress ip = IPAddress. any; IPEndPoint duan = new IPEndPoint (ip, 55555); s. bind (duan); textBox3.Text = "listener succeeded \ n"; // set the number of connections within the same time point s. listen (10); // wait for the user to connect to Thread t = new Thread (A); t. isBackground = true; t. start (s);} Socket socketsend; Dictionary <string, Socket> dic = new Dictionary <string, Socket> (); void A (object o) {while (true) {Socket s = o as Socket; socketsend = s. accept (); string name = socketsend. remoteEndPoint. toString (); dic. add (name, socketsend); comboBox1.Items. add (name); textBox3.AppendText ("connection successful \ n" + name + "\ n"); Thread tt = new Thread (B); tt. start (socketsend) ;}} private void formateload (object sender, EventArgs e) {Control. checkforillegalcrossthreadcils = false;} public void B (object oo) {Socket socketsend = oo as Socket; while (true) {byte [] B = new byte [1024*1024*2]; int a = socketsend. receive (B); if (a = 0) {break;} string receive = Encoding. default. getString (B, 0, a); textBox3.AppendText (receive + "\ n") ;}} private void button2_Click (object sender, EventArgs e) {byte [] by = System. text. encoding. default. getBytes (textBox4.Text); List <byte> B = new List <byte> (); B. add (0); B. addRange (by); byte [] cc = B. toArray (); dic [comboBox1.SelectedItem. toString ()]. send (cc); // socketsend. send (by);} private void button3_Click (object sender, EventArgs e) {OpenFileDialog dialog = new OpenFileDialog (); dialog. title = "select a file"; dialog. initialDirectory = @ "C: \ Users \ PC \ Desktop"; dialog. filter = "all files | *. * "; dialog. showDialog (); string name = dialog. fileName; textBox5.Text = name;} private void button5_Click (object sender, EventArgs e) {using (FileStream f = new FileStream (textBox5.Text, FileMode. open, FileAccess. read) {byte [] B = new byte [1024*1024*5]; int r = f. read (B, 0, B. length); List <byte> list = new List <byte> (); list. add (1); list. addRange (B); byte [] newby = list. toArray (); dic [comboBox1.SelectedItem. toString ()]. send (newby, 0, r + 1, SocketFlags. none) ;}} private void button4_Click (object sender, EventArgs e) {byte [] a = new byte [1]; a [0] = 2; dic [comboBox1.SelectedItem. toString ()]. send ();}}}

The following is the client code ..

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; using System. IO; namespace WindowsFormsC {public partial class Form1: Form {public Form1 () {InitializeComponent () ;}socket ss; private void button#click (object sender, EventArgs e) {ss = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); IPAddress ip = IPAddress. parse (textBox1.Text); IPEndPoint duan = new IPEndPoint (ip, Convert. toInt32 (textBox2.Text); ss. connect (duan); a ("successfully connected to the server"); Thread t = new Thread (B); t. start ();} void B () {while (true) {byte [] cc = new byte [1024*1024*2]; int ac = ss. receive (cc); if (ac = 0) {break;} if (cc [0] = 0) {a (Encoding. default. getString (cc, 1, AC-1); // 0 a length} else if (cc [0] = 1) {SaveFileDialog dia = new SaveFileDialog (); dia. title = "save the file"; dia. initialDirectory = @ "C: \ Users \ PC \ Desktop"; dia. filter = "all files | *. * "; dia. showDialog (this); using (FileStream s = new FileStream (dia. fileName, FileMode. openOrCreate, FileAccess. write) {s. write (cc, 0, AC-1); MessageBox. show ("saved successfully", "prompt") ;}} else if (cc [0] == 2) {for (int I = 0; I <1000; I ++) {this. location = new Point (200,200); this. location = new Point (250,250) ;}}} void a (string name) {textBox3.AppendText (name + "\ t \ n");} private void button2_Click (object sender, eventArgs e) {byte [] v = Encoding. default. getBytes (textBox4.Text); ss. send (v);} private void Form1_Load (object sender, EventArgs e) {Control. checkforillegalcrossthreadcils = false ;}}}

The applet function can send messages, vibrate, and transmit files ,,...

You can join the QQ Group for programming and learning ~!!!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.