Start Socket Programming C #

Source: Internet
Author: User

C # to write the socket program, overall is relatively convenient, Microsoft helped us do a lot of work. Socket programming a lot of applications, related information online is also a lot, because the work needs, a period of time also used in C # to write a socket program, here to write a record.

Create a socket on the server side, bind the specified interface with the Bind method, cause the socket to be associated with a local endpoint, and listen for requests on that interface through the Listen method, and when listening to the client connection, call accept to complete the operation of the connection. Create a new socket to handle incoming connection requests.

After using the socket, remember to disable the socket using the shutdown method and close the socket using the Close method

In C #, Microsoft provides the socket class

public class Socket:idisposable
{
Public Socket (AddressFamily addressfamily, SocketType sockettype, ProtocolType protocoltype);

//......

}

However, the socket class is not used directly when coding because there are two classes that are packaged better. TcpListener and TcpClient.

First, the service side, binding a port number, to open the service.

Using system;using system.collections.generic;using system.text;using system.net;using System.Net.Sockets;using System.io;using System.threading;namespace consolesocketserver{class Program {private static TcpListener TC        PServer = null;            static void Main (string[] args) {IPAddress IPAddress = Ipaddress.any;            TCPServer = new TcpListener (iPAddress, 999);            999 is the port number, can be arbitrarily changed 0-1024, mainly do not and what 80,8080 such as the common port number conflicts OH.            Tcpserver.start ();            Console.WriteLine ("Listener started ...");            byte[] msg = Encoding.UTF8.GetBytes ("server data");            byte[] bytes = new byte[256];                while (true) {TcpClient client = Tcpserver.accepttcpclient (); int i = client.                Client.receive (bytes);                Console.WriteLine ("Accept:" + Encoding.UTF8.GetString (bytes)); Client.                                Client.send (msg); Client.                Close ();            Thread.Sleep (1000);  }      }    }} 

The client will connect to the specified server via the TcpClient Connect method and send the data via the Send method, receiving the data. The specific code is as follows:

using System;using system.text;using system.collections;using system.net;using system.net.sockets;using System.IO;using System.threading;using System.collections.generic;namespace consolesocketclient{class Program {private stat        IC TcpClient client = new TcpClient (); static void Main (string[] args) {client.            Connect ("127.0.0.1", 999);//This is a native 999 port number Console.WriteLine ("Connection succeeded ...");            byte[] data = Encoding.UTF8.GetBytes ("client data"); Socket socket = client.            Client; Socket. Send (data, data.            Length, Socketflags.none);            Console.WriteLine ("Send Success" + Encoding.UTF8.GetString (data)); Socket.            Receive (data, socketflags.none);            Console.WriteLine ("Accept data" + Encoding.UTF8.GetString);        Console.readkey (); }        }    }

Of course, this is just a simple explanation of how the socket communication, the above is just a simple demonstration of code, only to help you learn, understand socket programming, socket in combat there are many ways to go. In the actual programming process, sockets are mostly related to multithreading. Without multi-threading, you can say that socket programming doesn't make much sense. Because the socket involves too much blocking, running, and waiting. If you have not done socket programming before, many times you will feel that the program is somehow not moving, or that there is no normal response. In fact, this time is often the program is in a blocking state. If there is no corresponding experience, there is always a strange feeling. The solution is to use multi-threaded approaches. Specifically how to do, the following article to write.

The code above is compiled in. NET 4.0.


Start Socket Programming C #

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.