Reprint: C#:socket Communication

Source: Internet
Author: User
Tags fully qualified domain name

Original address: http://www.cnblogs.com/s380774061/archive/2012/10/15/2725297.html

Had always wanted to make a C # socket code, has not been a start, tonight finally practiced a. The process is now prepared for later use.

Very simple source code.

Tool: Vs2010

Build Project: C # Console Application

Server code

Using system;using system.collections.generic;using system.linq;using system.text;//Add socket class using System.Net;using            System.net.sockets;namespace sockeconsoleserver{class Program {static void Main (string[] args) {            int port = 2000;            String host = "127.0.0.1";            Create endpoint IPAddress IP = ipaddress.parse (host);             IPEndPoint ipe = new IPEndPoint (ip,port); Create socket and start listening socket s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);    Create a socket object, using the Sockettyype.dgram type Socket S.bind (IPE) if the UDP protocol is used;    Bind the Endpoint object (2000 port and IP address) s.listen (0);            Start listening Console.WriteLine ("Waiting for Client Connection");   Accept the client connection, establish a new socket for this connection, and accept the message socket TEMP = s.accept ();            Create a new socket Console.WriteLine ("Establish Connection") for the newly established connection;            String recvstr = "";            byte[] recvbytes = new byte[1024];            int bytes; bytes = Temp. RecEive (recvbytes,recvbytes.length,0);            Receive Message from client Recvstr + = Encoding.ASCII.GetString (recvbytes, 0, bytes);    Return information Console.WriteLine ("Server Get message:{0}" to client side, RECVSTR); The message from the client is displayed as String sendstr = "ok!            Client Send Message successful! ";            byte[] bs = Encoding.ASCII.GetBytes (SENDSTR); Temp. Send (Bs,bs.  length,0); Returns information to the client temp.            Close ();            S.close ();        Console.ReadLine (); }    }}

  

Client code:

Using system;using system.collections.generic;using system.linq;using system.text;//Add the class using System.Net for the socket;        Using System.net.sockets;namespace socketconsoleclient{class Program {static void Main (string[] args)                {try {int port = 2000;                String host = "127.0.0.1";                Create endpoint endpoint IPAddress IP = ipaddress.parse (host);   IPEndPoint ipe = new IPEndPoint (IP, port);  Convert IP and port to IPEndPoint instance//create socket and connect to server socket c = new socket (AddressFamily.InterNetwork,   SocketType.Stream, PROTOCOLTYPE.TCP);                Create socket Console.WriteLine ("Connecting ..."); C.connect (IPE);                Connect to server//Send message to server string sendstr = "Hello,this is a socket test";   byte[] bs = Encoding.ASCII.GetBytes (SENDSTR);                Encodes a string into byte Console.WriteLine ("Send message"); C.send (BS, BS. Length, 0);                Send Message//accept the information returned from the server string recvstr = "";                byte[] recvbytes = new byte[1024];                int bytes;    bytes = C.receive (recvbytes, recvbytes.length, 0);                Receive return information from server Recvstr + = Encoding.ASCII.GetString (recvbytes, 0, bytes);    Console.WriteLine ("Client Get message:{0}", RECVSTR);                echo Back server return information console.readline ();            Remember to close c.close () after using the socket;            } catch (ArgumentException e) {Console.WriteLine ("Argumentnullexception:{0}", E);            } catch (SocketException e) {Console.WriteLine ("Socketexception:{0}", E); }        }    }}

  

After the code is knocked out, run down the server and use Netstat to listen for the usage of the lower port.

Server run interface (console interface)

Running the client (client console and Server console interface display)

Then use Netstat to listen for the lower port status.

The port is connected properly and the server is communicating properly with the client

Instructions for use with netstat:

Displays protocol statistics and current TCP/IP network connections.

NETSTAT [-A] [-b] [-e] [-f] [-n] [-O] [-P proto] [-r] [-S] [-t] [interval]

-a displays all connections and listening ports.
-B Displays the executable program involved in creating each connection or listening port.
In some cases, it is known that the executable program hosts multiple Independent
component, which in these cases shows when a connection or listening port is created
and a sequence of components. In this case, the name of the executable program
At the bottom [], the component it calls is located at the top, up to
to TCP/IP. Note that this option can be time-consuming and
May fail if sufficient permissions are available.
-e Displays Ethernet statistics. This option can be used in conjunction with the-s option.
-F Displays the fully qualified domain name (FQDN) of the external address.
-N Displays the address and port number in digital form.
-O Displays the ID of the process that you have associated with each connection.
-p proto shows the connection of proto specified protocol; Proto can be any of the following
What: TCP, UDP, TCPv6, or UDPV6. If the WITH-s option
Item is used to display statistics for each protocol, Proto can be any of the following
What: IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP
or UDPV6.
-r Displays the routing table.
-S displays statistics for each protocol. By default, the display
IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPV6
The-p option can be used to specify a default subnet.
-T displays the current connection offload status.
Interval re-displays the selected statistics, the number of seconds between each display pause.
Press CTRL + C to stop displaying the statistics again. If omitted, the Netstat
The current configuration information is printed once.

Reprint: C#:socket Communication

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: [email protected] 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.