The following code examples demonstrate how to use the Socket class as a client to connect to remote network services and as a server to listen for connections from remote clients.
来源-MSDN:http://msdn.microsoft.com/zh-cn/library/w89fhyex.aspx
客户端:
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 public class SynchronousSocketClient {
7
8 public static void StartClient() {
9 // Data buffer for incoming data.
10 byte[] bytes = new byte[1024];
11
12 // Connect to a remote device.
13 try {
14 // Establish the remote endpoint for the socket.
15 // This example uses port 11000 on the local computer.
16 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
17 IPAddress ipAddress = ipHostInfo.AddressList[0];
18 IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
19
20 // Create a TCP/IP socket.
21 Socket sender = new Socket(AddressFamily.InterNetwork,
22 SocketType.Stream, ProtocolType.Tcp );
23
24 // Connect the socket to the remote endpoint. Catch any errors.
25 try {
26 sender.Connect(remoteEP);
27
28 Console.WriteLine("Socket connected to {0}",
29 sender.RemoteEndPoint.ToString());
30
31 // Encode the data string into a byte array.
32 byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
33
34 // Send the data through the socket.
35 int bytesSent = sender.Send(msg);
36
37 // Receive the response from the remote device.
38 int bytesRec = sender.Receive(bytes);
39 Console.WriteLine("Echoed test = {0}",
40 Encoding.ASCII.GetString(bytes,0,bytesRec));
41
42 // Release the socket.
43 sender.Shutdown(SocketShutdown.Both);
44 sender.Close();
45
46 } catch (ArgumentNullException ane) {
47 Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
48 } catch (SocketException se) {
49 Console.WriteLine("SocketException : {0}",se.ToString());
50 } catch (Exception e) {
51 Console.WriteLine("Unexpected exception : {0}", e.ToString());
52 }
53
54 } catch (Exception e) {
55 Console.WriteLine( e.ToString());
56 }
57 }
58
59 public static int Main(String[] args) {
60 StartClient();
61 return 0;
62 }
63 }
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 public class SynchronousSocketClient {
7
8 public static void StartClient() {
9 // Data buffer for incoming data.
10 byte[] bytes = new byte[1024];
11
12 // Connect to a remote device.
13 try {
14 // Establish the remote endpoint for the socket.
15 // This example uses port 11000 on the local computer.
16 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
17 IPAddress ipAddress = ipHostInfo.AddressList[0];
18 IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
19
20 // Create a TCP/IP socket.
21 Socket sender = new Socket(AddressFamily.InterNetwork,
22 SocketType.Stream, ProtocolType.Tcp );
23
24 // Connect the socket to the remote endpoint. Catch any errors.
25 try {
26 sender.Connect(remoteEP);
27
28 Console.WriteLine("Socket connected to {0}",
29 sender.RemoteEndPoint.ToString());
30
31 // Encode the data string into a byte array.
32 byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
33
34 // Send the data through the socket.
35 int bytesSent = sender.Send(msg);
36
37 // Receive the response from the remote device.
38 int bytesRec = sender.Receive(bytes);
39 Console.WriteLine("Echoed test = {0}",
40 Encoding.ASCII.GetString(bytes,0,bytesRec));
41
42 // Release the socket.
43 sender.Shutdown(SocketShutdown.Both);
44 sender.Close();
45
46 } catch (ArgumentNullException ane) {
47 Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
48 } catch (SocketException se) {
49 Console.WriteLine("SocketException : {0}",se.ToString());
50 } catch (Exception e) {
51 Console.WriteLine("Unexpected exception : {0}", e.ToString());
52 }
53
54 } catch (Exception e) {
55 Console.WriteLine( e.ToString());
56 }
57 }
58
59 public static int Main(String[] args) {
60 StartClient();
61 return 0;
62 }
63 }
服务器端:
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 public class SynchronousSocketListener {
7
8 // Incoming data from the client.
9 public static string data = null;
10
11 public static void StartListening() {
12 // Data buffer for incoming data.
13 byte[] bytes = new Byte[1024];
14
15 // Establish the local endpoint for the socket.
16 // Dns.GetHostName returns the name of the
17 // host running the application.
18 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
19 IPAddress ipAddress = ipHostInfo.AddressList[0];
20 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
21
22 // Create a TCP/IP socket.
23 Socket listener = new Socket(AddressFamily.InterNetwork,
24 SocketType.Stream, ProtocolType.Tcp );
25
26 // Bind the socket to the local endpoint and
27 // listen for incoming connections.
28 try {
29 listener.Bind(localEndPoint);
30 listener.Listen(10);
31
32 // Start listening for connections.
33 while (true) {
34 Console.WriteLine("Waiting for a connection");
35 // Program is suspended while waiting for an incoming connection.
36 Socket handler = listener.Accept();
37 data = null;
38
39 // An incoming connection needs to be processed.
40 while (true) {
41 bytes = new byte[1024];
42 int bytesRec = handler.Receive(bytes);
43 data += Encoding.ASCII.GetString(bytes,0,bytesRec);
44 if (data.IndexOf("<EOF>") > -1) {
45 break;
46 }
47 }
48
49 // Show the data on the console.
50 Console.WriteLine( "Text received : {0}", data);
51
52 // Echo the data back to the client.
53 byte[] msg = Encoding.ASCII.GetBytes(data);
54
55 handler.Send(msg);
56 handler.Shutdown(SocketShutdown.Both);
57 handler.Close();
58 }
59
60 } catch (Exception e) {
61 Console.WriteLine(e.ToString());
62 }
63
64 Console.WriteLine("\nPress ENTER to continue");
65 Console.Read();
66
67 }
68
69 public static int Main(String[] args) {
70 StartListening();
71 return 0;
72 }
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 public class SynchronousSocketListener {
7
8 // Incoming data from the client.
9 public static string data = null;
10
11 public static void StartListening() {
12 // Data buffer for incoming data.
13 byte[] bytes = new Byte[1024];
14
15 // Establish the local endpoint for the socket.
16 // Dns.GetHostName returns the name of the
17 // host running the application.
18 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
19 IPAddress ipAddress = ipHostInfo.AddressList[0];
20 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
21
22 // Create a TCP/IP socket.
23 Socket listener = new Socket(AddressFamily.InterNetwork,
24 SocketType.Stream, ProtocolType.Tcp );
25
26 // Bind the socket to the local endpoint and
27 // listen for incoming connections.
28 try {
29 listener.Bind(localEndPoint);
30 listener.Listen(10);
31
32 // Start listening for connections.
33 while (true) {
34 Console.WriteLine("Waiting for a connection");
35 // Program is suspended while waiting for an incoming connection.
36 Socket handler = listener.Accept();
37 data = null;
38
39 // An incoming connection needs to be processed.
40 while (true) {
41 bytes = new byte[1024];
42 int bytesRec = handler.Receive(bytes);
43 data += Encoding.ASCII.GetString(bytes,0,bytesRec);
44 if (data.IndexOf("<EOF>") > -1) {
45 break;
46 }
47 }
48
49 // Show the data on the console.
50 Console.WriteLine( "Text received : {0}", data);
51
52 // Echo the data back to the client.
53 byte[] msg = Encoding.ASCII.GetBytes(data);
54
55 handler.Send(msg);
56 handler.Shutdown(SocketShutdown.Both);
57 handler.Close();
58 }
59
60 } catch (Exception e) {
61 Console.WriteLine(e.ToString());
62 }
63
64 Console.WriteLine("\nPress ENTER to continue");
65 Console.Read();
66
67 }
68
69 public static int Main(String[] args) {
70 StartListening();
71 return 0;
72 }
73 }