C # network WinForm (iii)

Source: Internet
Author: User

C # Network WinForm (III.) One, TCP/IP hierarchy model

Application Layer (Application): The application layer is a very broad concept, there are some basic same system-level TCP/IP applications and application protocols, there are many enterprise applications and Internet applications. The HTTP protocol runs at the application level.

Transport Layer (Tanspot): The transport layer includes UDP and TCP,UDP almost no packets are checked, while TCP provides a transmission guarantee.

Network Layer (NETWOK): The network layer protocol consists of a series of protocols, including ICMP, IGMP, RIP, OSPF, IP (V4,V6), and so on.

Link Layer (link): Also known as the Physical Data network interface layer, responsible for message transmission.

Second, port
    • Port number range: 0-65535, which can represent a total of 65,536

By port number can be divided into 3 major categories

(1) Recognized ports (wellknownports): from 0 to 1023, they are tightly bound (binding) to some services. Usually the communication of these ports clearly indicates the protocol of a certain service. For example: Port 80 is actually always HTTP traffic.

(2) Registration port (registeredports): from 1024 to 49151. They are loosely tied to some services. This means that there are many services bound to these ports, which are also used for many other purposes. For example: Many systems handle dynamic ports starting around 1024.

(3) dynamic and/or private ports (dynamicand/orprivateports): from 49152 to 65535. In theory, these ports should not be assigned to the service. In fact, machines typically allocate dynamic ports from 1024 onwards.

    • Once a computer in the network is identified by an IP address, there may be many applications on the computer that provide services, each of which corresponds to a port.

1, the Internet host generally run a number of service software, while providing several services, each service opens a socket, and bound to a port, different ports corresponding to different services (applications)

For example: HTTP using port 80, FTP using 21 port SMTP using 25 port

Third, Socket general application Mode (server side and client)

Server-side sockets (minimum of two required)
One is responsible for receiving client connection requests (but is not responsible for communicating with the client)
Another socket responsible for generating a corresponding complex communication on the server side and communicating with the client when the connection to the client is successfully received

Communication Process Server side:
01, apply for a socket
02, bound to an IP address and on a port
03, turn on Listen, wait for receive connection
04, after the server receives the connection request, produces a new socket (port greater than 1024) and the client to establish a connection and communication, the original monitor socket continues to listen. The socket responsible for communication cannot be created indefinitely, and the number created is related to the operating system.

Socket for Client
You must specify the server address and port to connect to
Initializes a server-side TCP connection by creating a socket object

Communication Process Client:
01, apply for a socket
02, Connection server (indicates IP address and port number)

Four. The socket constructor
  Public Socket(AddressFamily addressFamily,SocketType  socketType,ProtocolType  protocolTYpe)
    • Parameter list:
      AddressFamily: Specifies the addressing scheme that the socket uses to resolve addresses. For example: internetwork Indicates when the socket is connected using an IP version 4 address
      SocketType: Defines the type of socket to open
      The socket class uses the ProtocolType enumeration to notify the Windows Sockets API of the requested protocol
    • Port number:
      1, the port number must be between 1 and 65535, preferably after 1024.
      2, the remote host to be connected must be listening on the specified port, that is, you are not free to connect to the remote host.
Five. Sockets common classes and APIs
    • Related classes:
   IPAddress:包含了一个IP地址   IPEndPoint:包含了一对IP地址和端口号
    • Method:
   Socket():创建一个Socket   Bind():绑定一个本地的IP和端口号(IPEndPoint)   Listen():让Socket侦听传入的连接吃那个病,并指定侦听队列容量   Connect():初始化与另一个Socket的连接   Accept():接收连接并返回一个新的Socket   Send():输出数据到Socket   Receive():从Socket中读取数据   Close():关闭Socket,销毁连接
Six. WinForm Example
Server private void Form1_Load (object sender, EventArgs e) {control.checkforillegalcrossthreadcalls = FA        Lse   } private void Btnlisten_click (object sender, EventArgs e) {//ip address IPAddress IP = ipaddress.parse (txtip.text);    IPAddress IP = ipaddress.any; Port number IPEndPoint point=new IPEndPoint (ip,int.    Parse (Txtport.text));    Socket socket=new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);    After you create the socket, you must tell the IP address and port number of the socket binding. Let the socket listen to the socket on which port the point try {//socket listens.        Bind (point); Come over 10 clients at the same point in time, and queue up a socket.        Listen (10);        ShowMsg ("server starts listening");        Thread thread = new Thread (acceptinfo); Thread.        IsBackground = true; Thread.    Start (socket); } catch (Exception ex) {ShowMsg (ex.    Message); }}//Record communication with socketdictionary<string,socket> dic=new dictionary<string, socket> ();//Private Sock ET client;void acceptinfo (object o) {   Socket socket = o as socket; while (true) {//communication with socket try {//create communication with socket socket Tsocket = socket.          Accept ();            String point = TSocket.RemoteEndPoint.ToString (); IPEndPoint endPoint = (ipendpoint) client.            Remoteendpoint;         string me = Dns.gethostname ();//Get the native name//messagebox.show (me); ShowMsg (Point + "Connection succeeded!         ");         CBOIPPORT.ITEMS.ADD (point); Dic.            ADD (Point, Tsocket);            Receive message thread th = new Thread (RECEIVEMSG); Th.            IsBackground = true; Th.        Start (Tsocket); } catch (Exception ex) {ShowMsg (ex.            Message);        Break    }}}//Receive Message void Receivemsg (object o) {socket client = O as socket; while (true) {//Receive client sent over data try {//define byte array to hold data received from client byte[] buffer =            New byte[1024 * 1024]; Puts the received data into buffer and returns the length of the actual accepted data intn = client.            Receive (buffer);            Converts bytes to string words = Encoding.UTF8.GetString (buffer, 0, N); ShowMsg (client.        Remoteendpoint.tostring () + ":" + words); } catch (Exception ex) {ShowMsg (ex.            Message);        Break }}}} void ShowMsg (String msg) {txtlog.appendtext (msg+ "\ r \ n");} private void Form1_formclosing (object sender, FormClosingEventArgs e) {//close child thread when main form closes}//Send message to client private void Btns        End_click (object sender, EventArgs e) {try {showmsg (txtmsg.text);        string ip = cboipport.text;        byte[] buffer = Encoding.UTF8.GetBytes (Txtmsg.text); DIC[IP].        Send (buffer); Client.    Send (buffer); } catch (Exception ex) {ShowMsg (ex.    Message); }}
Clients socket client = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);p rivate void    Btnconnection_click (object sender, EventArgs e) {///connection to the destination IP IPAddress IP = ipaddress.parse (txtip.text);    IPAddress IP = ipaddress.any; Which app (port number) to connect to the destination IP? ) IPEndPoint point=new IPEndPoint (ip,int.    Parse (Txtport.text)); try {//Connect to server client.        Connect (point);        ShowMsg ("Connection succeeded"); ShowMsg ("Server" + client.)        Remoteendpoint.tostring ()); ShowMsg ("Client:" + client.)        Localendpoint.tostring ());        After the connection is successful, you can receive the message sent by the server thread Th=new thread (receivemsg); Th.        IsBackground = true; Th.    Start (); } catch (Exception ex) {ShowMsg (ex.    Message);            }}//receive Server message void Receivemsg () {while (true) {try {byte[] buffer = new byte[1024 * 1024]; int n = client.            Receive (buffer);            string s = Encoding.UTF8.GetString (buffer, 0, N); ShowMsg (client. Remoteendpoint.tostriNg () + ":" + s); } catch (Exception ex) {ShowMsg (ex.            Message);        Break }}}void ShowMsg (String msg) {txtinfo.appendtext (msg+ "\ r \ n");}            private void Btnsend_click (object sender, EventArgs e) {//client sends message to server if (Client!=null) {try {            ShowMsg (Txtmsg.text);            byte[] buffer = Encoding.UTF8.GetBytes (Txtmsg.text); Client.        Send (buffer); } catch (Exception ex) {ShowMsg (ex.        Message); }}}private void Clientform_load (object sender, EventArgs e) {control.checkforillegalcrossthreadcalls = false;}

C # network WinForm (iii)

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.