In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to realize the Socket communication of C#". The editor shows you the operation process through the actual case, the operation method is simple and fast, and the practicality is strong. I hope this article "how to realize the Socket communication of C#" can help you solve the problem.
What is socket
Socket is the middle software abstraction layer for the communication between the application layer and the TCP/IP protocol family, and it is a group of interfaces. In the design pattern, Socket is actually a facade pattern, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a simple set of interfaces is all, allowing Socket to organize the data to comply with the specified protocol. Therefore, we do not need to have an in-depth understanding of the tcp/udp protocol, socket has been packaged for us, we just need to follow the rules of socket to program, the program naturally follows the tcp/udp standard.
Second, the work flow of sockets
Let's start with the server side. The server initializes Socket, then binds to the port (bind), listen the port, calls accept blocking, and waits for the client to connect. At this point, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, finally closes the connection, and an interaction ends.
3. Server private void btnListen_Click (object sender, EventArgs e) {IPEndPoint point = new IPEndPoint (IPAddress.Any, 13000); / / IPAddress.Any any local network card IP. Local port view netstat-an / / server Socket definition Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind (point); / / bind IP socket.Listen (10); / / start listening. Maximum number of listeners, 10 clients queued up at the same time ("Server starts listening"); Thread thread = new Thread (AcceptInfo); thread.Start (socket);} / / SocketDictionary dic for recording communication = new Dictionary (); / / private Socket client;void AcceptInfo (object o) {Socket socket = o as Socket While (true) {/ / Communication socket try {Socket clientSocket = socket.Accept (); / / if the client has a request, generate a new Socket string point = clientSocket.RemoteEndPoint.ToString (); ShowMsg (point + "connect to the client successfully!") ; dic.Add (point, clientSocket); / / receive message Thread th = new Thread (ReceiveMsg); th.Start (clientSocket);} catch (Exception ex) {break;}} socket.Close ();} / / receive message void ReceiveMsg (object socket) {Socket clientSocket = socket as Socket While (true) {/ / data sent by the client try {/ / define the byte array to store the data received from the client byte [] buffer = new byte [1024 * 1024]; int n = clientSocket.Receive (buffer) / / put the received data into buffer and return the length of the actual accepted data / / convert bytes into the string string words = Encoding.Unicode.GetString (buffer, 0, n); Console.WriteLine (clientSocket.RemoteEndPoint.ToString () + ":" + words); byte [] msg = Encoding.Unicode.GetBytes (words); clientSocket.Send (msg) / / send data, byte array} catch (Exception ex) {break;}} clientSocket.Shutdown (SocketShutdown.Both); / / disable sending and receiving data clientSocket.Close (); / / close socket and release resources} IV. Client Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint point = new IPEndPoint ("127.0.0.1", 13000)) / / IPclientSocket.Connect (point) connected to the server; / / connected to the server ShowMsg ("connected successfully"); ShowMsg ("server" + client.RemoteEndPoint.ToString ()); ShowMsg ("client:" + client.LocalEndPoint.ToString ()); Thread th = new Thread (ReceiveMsg); / / after the connection is successful, you can receive messages from the server th.IsBackground = true;th.Start (); clientSocket.Shutdown (SocketShutdown.Both) / / prohibit sending and receiving data clientSocket.Close (); / / close socket and release resources 5. Member 1 of the Socket object. The attribute name indicates that AddressFamily acquires the address family of Socket. Available gets the amount of data that has been received from the network and is available for reading. Blocking gets or sets a value indicating whether Socket is in blocking mode. Connected gets a value indicating whether Socket connects to the remote host during the last Send or Receive operation. Handle gets the operating system handle to Socket. LocalEndPoint gets the local endpoint. RemoteEndPoint gets the remote endpoint. ProtocolType gets the protocol type of Socket. SocketType gets the type of Socket. ReceiveBufferSize gets or sets a value that specifies the size of the Socket receive buffer. ReceiveTimeout gets or sets a value that specifies the length of time that the synchronous Receive call will time out later. SendBufferSize gets or sets a value that specifies the size of the Socket send buffer. SendTimeout gets or sets a value that specifies the length of time that the synchronous Send call will time out later. 2. Methods
Accept
The name indicates that Accept () creates a new Socket for the new connection. BeginAccept (AsyncCallback, Object) starts an asynchronous operation to accept an incoming connection attempt. EndAccept (Byte [], IAsyncResult) accepts incoming connection attempts asynchronously and creates a new Socket object to handle remote host communication. This method returns a buffer containing the initial data transferred. AcceptAsync (SocketAsyncEventArgs) starts an asynchronous operation to accept an incoming connection attempt.
Connect
The name indicates that Connect (EndPoint) establishes a connection with the remote host. BeginConnect (EndPoint, AsyncCallback, Object) starts an asynchronous request for a remote host connection. EndConnect (IAsyncResult) ends a pending asynchronous connection request. ConnectAsync (SocketAsyncEventArgs) starts an asynchronous request for a remote host connection.
Disconnect
The name indicates that Disconnect (Boolean) closes the socket connection and allows socket reuse. BeginDisconnect (Boolean, AsyncCallback, Object) begins an asynchronous request to disconnect from the remote endpoint. EndDisconnect (IAsyncResult) ends a pending asynchronous disconnect request. DisconnectAsync (SocketAsyncEventArgs) closes socket connections and allows socket reuse.
Receive
The name indicates that Receive (Byte []) receives data from the bound Socket socket and stores the data in the receive buffer. BeginReceive (Byte [], Int32, Int32, SocketFlags, AsyncCallback, Object) begins to receive data asynchronously from the connected Socket. EndReceive (IAsyncResult) ends a pending asynchronous read. ReceiveAsync (SocketAsyncEventArgs) starts an asynchronous request to receive data from the connected Socket object.
ReceiveFrom
The name indicates that ReceiveFrom (Byte [], EndPoint) receives the Datagram into the data buffer and stores the endpoint. BeginReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) begins to receive data asynchronously from a specified network device. EndReceiveFrom (IAsyncResult, EndPoint) ends a pending asynchronous read from a specific endpoint. ReceiveFromAsync (SocketAsyncEventArgs) begins to receive data asynchronously from a specified network device.
ReceiveMessageFrom
The name description ReceiveMessageFrom (Byte [], Int32, Int32, SocketFlags, EndPoint, IPPacketInformation) uses the specified SocketFlags to receive the specified number of bytes of data to the specified data buffer location, and stores the endpoint and packet information. BeginReceiveMessageFrom (Byte [], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) starts to use the specified SocketFlags to asynchronously receive the specified number of bytes of data to the specified location of the data buffer, and then stores the endpoint and packet information. EndReceiveMessageFrom (IAsyncResult, SocketFlags, EndPoint, IPPacketInformation) ends a pending, asynchronous read from a specific endpoint. This method also displays more information about packets than about EndReceiveFrom (IAsyncResult, EndPoint). ReceiveMessageFromAsync (SocketAsyncEventArgs) begins to use the specified SocketFlags to asynchronously receive data with a specified number of bytes to the specified location of the data buffer and store endpoint and packet information.
Send
The name indicates that Send (Byte []) sends the data to the connected Socket. BeginSend (Byte [], Int32, Int32, SocketFlags, AsyncCallback, Object) sends data asynchronously to the connected Socket. EndSend (IAsyncResult) ends a pending asynchronous send. SendAsync (SocketAsyncEventArgs) asynchronously sends data to the connected Socket object.
SendFile
The name indicates that SendFile (String) uses the Socket transfer flag to send the file fileName to the connected UseDefaultWorkerThread object. BeginSendFile (String, AsyncCallback, Object) uses the Socket flag to send the file fileName to the connected UseDefaultWorkerThread object. EndSendFile (IAsyncResult) ends the pending asynchronous sending of files.
SendTo
The name indicates that SendTo (Byte [], EndPoint) sends data to the specified endpoint. BeginSendTo (Byte [], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) sends data to a specific remote host asynchronously. EndSendTo (IAsyncResult) ends a pending asynchronous send to a specified location. SendToAsync (SocketAsyncEventArgs) sends data to a specific remote host asynchronously.
Other
Name description Select (IList, Int32) determines the state of one or more sockets. SendPacketsAsync (SocketAsyncEventArgs) sends a collection of files or data buffers in memory to the connected Socket object asynchronously. Bind (EndPoint) associates the Socket with a local endpoint. Listen (Int32) puts the Socket in the listening state. CancelConnectAsync (SocketAsyncEventArgs) cancels an asynchronous request for a remote host connection. GetSocketOption (SocketOptionLevel, SocketOptionName) returns the value of the specified Socket option, expressed as an object. SetSocketOption (SocketOptionLevel, SocketOptionName, Boolean) sets the specified Socket option to the specified Boolean value. SetIPProtectionLevel (IPProtectionLevel) sets the IP protection level of the socket. Shutdown (SocketShutdown) disables sending and receiving on a Socket. Close () closes the Socket connection and releases all associated resources. Dispose () releases all resources used by the current instance of the Socket class. This is the end of the content about "how to realize the Socket Communication of C#". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.