Communication Programming 2-socket of medium difficulty

Source: Internet
Author: User
Tags getstream

The same thing --- socket. This is a little difficult. To improve the fun of the program, I think of an example I saw before the Chinese New Year-something similar to QQ, but only two people can
Chat with each other, and it is worth a try if you have friends who have local networks. This article is generally difficult. Although the current teachers think that their ability to speak things is poor, I will do my best.
Explain the following examples
In this example, server programs and client programs are divided into the following content:
1 tcplistener create a server listener
Tcplistener Len = new tcplistener (port );
The parameter is the port number, which is used to identify the program. In this case, have many users ever played Mu private servers or? Remember to change the port number when the Mu private server has no login Device
Is it 44405 ?? The number 44405 indicates that the Mu game should have such an identifier. When you run the Mu private server client, it will not connect to the legendary server.
2 start listening
Len. Start ();
3. Pending connection requests
Socket S = Len. acceptsocket ();
If the acceptsocket () is successful, a socket type is returned.
4. Create a working Channel
Networkstream NS = new networkstream (s); Establish an NS channel on this socket. Note that ns is of the networkstream type.
For the client, you need to use the following:
1 tcpclient usage:
Tcpclient CLI = new tcpclient (); that is, instantiate a tcpclient called cli. Note that it must be instantiated.
2 connect (endpoint, port number );
After creating a tcpclient, you need to "bind" the connection to its corresponding port. For example, if the IP address on the server side is 192.168.0.4 and the port is 4500
1. Create an IPaddress
IPaddress IP = IPaddress. parse ("192.168.0.4 ");
2. Use it as a parameter.
Server. Connect (IP, 4500); this connection is the connection to the server program we are going to do.
Note that 2: 1st, you need to establish a connection on some instances. Here there are some May 2nd, and many program numbers have occupied the port number. For example, if I say 4500 here, you may
Another program on the computer is this number, and the same number cannot be used in two programs. You need to change the number. You may say: I don't know which ones are occupied. Yes, 1st
It is best to use it before 1024. It should be used by many system programs, 2nd. If the Program no. 4500 has been used, you will be prompted when debugging is complete.
Generally, a port number can only be used once. If you encounter such a prompt, change the number.
3 closed channels
I just established a server-side channel, NS, but this channel is not closed. Where is the end point of NS? Not Specified
Networkstream output = cle. getstream ();
Getstream originally meant "Get stream". Further, what stream is obtained? Let's take a look at cle. getstream (). We know that it is obtained from CLE, and CLE uses cle. Connect.
Connect to the server, so we get the conclusion that the Stream Obtained by CLE. getstream () (I understand it as "the channel obtained ")
Now that you have created a channel ns in front, and now you can use the "get channel" on the client, the working channel is closed now. You may want to ask the role of this channel and the channel.
You can recall what the function of filestream is, and you will know the function of networkstream.

Now, let's talk about this thing: system. Io. binarywriter is used to write data to a specified channel. Of course, there are also system. Io. binaryreader.
We also need to review how system. Threading can create multiple threads. Generally, what is a form running in main? Is application. Run (New Form ());
Yes, it is a form, but the server behind the form is also running. This is a dual-running program (foreground form operation and background server operation) in fact, many programs that are slightly larger are multithreading.
For example, if you press Windows Task Manager, all the processes you see in the process bar are multiple threads on your machine.

Now, I want to write a program. I wanted to draw a few pictures to help me understand it, because I can only upload 15 K of content. The figure is omitted.
1. Create a server first
Both the server side and the client side are composed of one form, two RichTextBox, and one by ox. Two RichTextBox are inrichtextbox and derichtextbox, respectively. For example, Enter Text in inrichtextbox.
"Hello" server and client derichtextbox both Display Server> "hello". Similarly, enter "you" in the inrichtextbox of the client, and derichtextbox on the server and client.
The client> "you" is displayed. The Code is as follows:
Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. net. Sockets;
Using system. net;
Using system. IO;
Using system. Threading;

Namespace network communication 2a
{
/// <Summary>
/// Summary of form1.
/// </Summary>
Public class server: system. Windows. Forms. Form
{
Private system. Windows. Forms. RichTextBox extends textbox1;
Private system. Windows. Forms. RichTextBox inrichtextbox2;
Private system. Windows. Forms. Button button1;
Private system. net. sockets. networkstream ns;
Private system. Threading. Thread th;
Private socket S;
Private system. Io. binaryreader re;
Private system. Io. binarywriter WR;
Private string Rong;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;

Public server ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
Th = new thread (New threadstart (runserver ));
Th. Start ();

//
// Add Any constructor code after calling initializecomponent
//
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.

# Endregion

/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (new server ());
}

Private void button#click (o B j e c t sender, system. eventargs E)
{
If (s! = NULL)
Wr. Write ("Server>" + this. inrichtextbox2. Text );
This. Define textbox1. Text + = "\ r \ nserver>" + this. inrichtextbox2. text;
If (this. inrichtextbox2. Text = "CLE ")
S. Close ();
This. inrichtextbox2. Clear ();

}
Public void runserver ()
{
Try
{
Tcplistener Len = new tcplistener (4700); // create a listener
Len. Start (); // start listening
While (true) // uses an infinite loop and transmits information through socket-based NS infinitely.
{
This. Wait textbox1. Text = "wait, no connection is available! ";
S = Len. acceptsocket (); // create a socket and suspend the connection request
NS = new networkstream (s); // create an NS channel on this socket
WR = new binarywriter (NS); // WR is used to write services for this channel
Re = new binaryreader (NS); // re read service for this channel
/* It is worth noting that WR and RE can be connected to the program with a 4700 fracture. wr can only be written to the connected program, and RE can only be read to the connected program, this is different from reading and writing in fliestream. When filestream is set up to read and write, it must define a local location, which is a dead location, here, the location of WR and RE is completely dependent on ns and what program is connected to form a complete closed channel */
This. Adjust textbox1. Text + = "now connected, haha :)";

Do
{
Try
{
Rong = Re. readstring ();
This. Optional textbox1. Text + = "\ r \ n" + Rong;
}
Catch (exception)
{Break ;}
} While (Rong! = "Clent >>> CLE ");
Wr. Close (); Re. Close (); NS. Close (); S. Close ();

}

}
Catch (exception ERR)
{
MessageBox. Show (ERR. Message );}
}

Private void server_closing (o B j e c t sender, system. componentmodel. canceleventargs E)
{
System. environment. Exit (system. environment. exitcode );
}
}
}

2 customer satin
Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. net;
Using system. net. Sockets;
Using system. IO;
Using system. Threading;

Namespace network communication 2B
{
/// <Summary>
/// Summary of form1.
/// </Summary>
Public class client: system. Windows. Forms. Form
{
Private system. Windows. Forms. RichTextBox inrichtextbox1;
Private system. Windows. Forms. RichTextBox extends textbox2;
Private system. Windows. Forms. Button button1;
Private system. Windows. Forms. Button button2;
Private thread th;
Private system. Io. binarywriter WR;
Private system. Io. binaryreader re;
Private string mess;
Private system. net. sockets. networkstream output;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;

Public client ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
Th = new thread (New threadstart (runclient ));
Th. Start ();
// Add Any constructor code after calling initializecomponent
//
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
// Button1
//
This. button1.location = new system. Drawing. Point (32,176 );
This. button1.name = "button1 ";
This. button1.size = new system. Drawing. Size (59, 23 );
This. button1.tabindex = 2;
This. button1.text = "button1 ";
//
// Button2
//
This. button2.anchor = (system. Windows. Forms. anchorstyles) (system. Windows. Forms. anchorstyles. Top | system. Windows. Forms. anchorstyles. Right )));
This. button2.location = new system. Drawing. Point (280,176 );
This. button2.name = "button2 ";
This. button2.size = new system. Drawing. Size (59, 23 );
This. button2.tabindex = 3;
This. button2.text = "send ";
This. button2.click + = new system. eventhandler (this. button2_click );
//
// Client
//
This. autoscalebasesize = new system. Drawing. Size (6, 14 );
This. clientsize = new system. Drawing. Size (392,349 );
This. Controls. Add (this. button2 );
This. Controls. Add (this. button1 );
This. Controls. Add (this. extends textbox2 );
This. Controls. Add (this. inrichtextbox1 );
This. Name = "client ";
This. Text = "client ";
This. Closing + = new system. componentmodel. canceleventhandler (this. client_closing );
This. resumelayout (false );

}
# Endregion

/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (new client ());
}

Private void button2_click (o B j e c t sender, system. eventargs E)
{
Wr. Write ("client >>>" + this. inrichtextbox1. Text );
This. Define textbox2. Text + = "\ r \ nclient >>>" + this. inrichtextbox1. text;
This. inrichtextbox1. Clear ();
}
Public void runclient ()
{

Tcpclient CLE;
Try
{
This. initialize textbox2. Text + = "the client starts now ........";

CLE = new tcpclient ();
File: // IPaddress IP = IPaddress. parse ("192.168.0.33"); // connect to the server
CLE. Connect ("localhost", 4700 );
Output = cle. getstream (); // connect to the server channel. Now the channel is closed
WR = new binarywriter (output); // read/write operations through this channel
Re = new binaryreader (output );
Do
{
Try
{
Mess = Re. readstring (); // The "read" device of this channel reads the information transmitted by the server and is displayed in the "output" text basket.
This. Optional textbox2. Text + = "\ r \ n" + mess;
}
Catch (exception)
{System. environment. Exit (1 );}
}
While (mess! = "Server> CLE ");
This. Disable textbox2. Text + = "\ r \ n disabled ~ ";
Wr. Close (); Re. Close (); output. Close (); cle. Close ();
Application. Exit ();
}
Catch (exception ERR) {MessageBox. Show (ERR. Message );}
}

Private void client_closing (o B j e c t sender, system. componentmodel. canceleventargs E)
{
System. environment. Exit (system. environment. exitcode );
}
}
}

In this way, two forms can communicate with each other. The private void client_closing (o B j e c t sender, system. componentmodel. canceleventargs E) is indispensable. You have closed the form but 2nd threads are still running. In this case, you can only use
Windows Task Manager to end the process.

Okay. I am leaving a question for everyone to think about. Now, for example, how can I enable one-to-one communication between four client programs ?? How can we make them communicate collectively?
Tip: the principle of on-demand video and broadcast is as follows. You 'd better not watch it right away. Think about it first.

If there are four sub-computers, four clients (for example, a. B .c.d) and one server are required. All four clients have CLI. connect () to this server, there should be 4 output = cle. getstream ();
For example, they are ooutput1 = cle1.getstream (); utput2 = cle2.getstream (); output3 = cle3.getstream (); output4 = cle4.getstream (); that is, four channels need to be created.
A and B need to communicate. A first communicates with the server, and the server obtains a information, which is then sent to B through the channel between the server and B.

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.