C # Network Programming

Socket Programming

Socket Chinese translation of the socket, called Socket fact, network transmission endpoint abstract representation.
So, what are you end? It is actually in the transmission network transmission starting point or an end point, but the starting point or end point is rather special, it is composed of two parts: ip address and port number, with: forms (Ip address port number) representation. A socket is the basic operation of the network communication unit for TCP / IP.
So, what is the TCP / IP network communication it? This is a very broad concept, he said bluntly, we are now using the Internet is based on this architecture research and development, which is the basis of the communication infrastructure of the Internet. The concept involves particularly high. For example, IP, TCP / UDP protocol, ICMP, and we are more familiar with http, ftp, but in C # network programming among the most commonly used is TCP / UDP concept, look at the two concepts, as well as related programming method, you can deal with it on a network programming.

TCP protocol

Refer to this blog post
tcp protocol detailed

Socket programming, we can build the proposed client and the server, and the code follows the steps:
Socket programming -Tcp server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Socket_Tcp
{
class Program
{
static void Main(string[] args)
{
//服务器端
//1.创建socket
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Binding // ip address and port number (each software will have a port number)
the IPAddress the IPAddress ipAddress = new new (new new byte [] {} 192,168,101,8); // check the IP address can use the ipconfig
the EndPoint = new new endPoint, the IPEndPoint (ipAddress, 2333); // IPEndPoint ip address and port number for the package, written in 2333 is just a port number
tcpServer.Bind (endPoint);

// start listening
tcpServer.Listen (150); // allows up to 150 clients to connect

// clientSocket for customers to return client message
Socket clientSocket = tcpServer.Accept (); // pauses the current thread until after a client connection, and then execute the following line of code in the
string message = "My message to the client." ;
var = bypeMessage Encoding.UTF8.GetBytes (Message); // convert to byte Message type
clientSocket.Send (bypeMessage);

// returns the received client message
byte [] backDate = new byte [ 1024]; // for receiving a message returned by the server
int length = clientSocket.Receive (backDate);
String backMessage = Encoding.UTF8.GetString (backDate, 0 , length);
Console.WriteLine (backMessage);
the Console.ReadKey ();
}
}
}

client socket programming -Tcp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Socket_Tcp_Client
{
class Program
{
static void Main(string[] args)
{
//客户端
//创建Socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// initiate a request to establish a connection
IPAddress ipAddress = IPAddress.Parse ( "192.168.101.8");
EndPoint endPoint = new new IPEndPoint (ipAddress, 2333);
tcpClient.Connect (endPoint); // client does not need to listen, but to and server connection, and Ip address and port number to the server and consistent
byte [] date = new new byte [1024];
int length = tcpClient.Receive (date); // store received data over a date, length is the length

string message = Encoding.UTF8.GetString (date, 0 , length); // converts the received date type string
Console.WriteLine (message);

// returns a message to the server
string backMessage = Console.ReadLine (); // returns the message input by the user
tcpClient.Send (Encoding.UTF8.GetBytes (backMessage)); // send a message to the server

Console.ReadKey();
}
}
}

UDP protocol

Refer to this blog post
UDP protocol learning

This blog post which has been described in such situations:
1. First, UDP is a connectionless protocol, so compare programmatically TCP protocol, we can easily find less to establish a connection among the UDP process.
2.UDP protocol is a datagram protocol, the TCP protocol is different from the embodiment Stream employed, instead of using Dgram way, this is also reflected in the programming Socket them.

UDP server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace udp_server
{
class Program
{
private static Socket udpServer;
static void Main(string[] args)
{
//创建Socket
udpServer = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);

//绑定ip和端口号
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.101.8"),2333));

//接收数据
new Thread(ReceiveMessage) { IsBackground = true }.Start();//设置成后台线程,因为程序运行结束,也就不需要这个线程了。


udpServer.Close();
Console.ReadKey();
}

private static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);

string message = Encoding.UTF8.GetString(data, 0, length);

Console.WriteLine("从ip: " + (remoteEndPoint as IPEndPoint).Address.ToString()
+ (remoteEndPoint as IPEndPoint).Port + "收到了数据: " + message);
}
}
}
}

UDP客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22大专栏  C#网络编程pan>
23
24
25
26
27
28
29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace udp_socket_Client
{
class Program
{
static void Main(string[] args)
{
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram
, ProtocolType.Udp);
//发送数据
while (true)
{
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.101.8"), 2333));
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
}

Console.ReadKey();
}
}
}

监听器

TCP和UDP编程除了可以使用Socket以外,还可以使用TcpListener和UdpClient,具体编码和步骤如下所示。

TcpListener

服务器端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Tcplistener_Server
{
class Program
{
static void Main(string[] args)
{
//1.对socket进行封装,tcpListener内本身包含套接字
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.101.8"),2223);

//2.进行监听
listener.Start();

//3.等待用户连接
TcpClient client = listener.AcceptTcpClient();

//4.获得客户端发送过来的数据
NetworkStream stream = client.GetStream();

//5.读取数据
byte[] data = new byte[1024];
while (true)
{
int length = stream.Read(data, 0, 1024);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("Receive Message: " + message);
}
stream.Close();
client.Close();
listener.Stop();
}
}
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Tcplistener_Cllient
{
class Program
{
static void Main(string[] args)
{
//1.创建TCP对象的时候,就会与服务器建立联系
TcpClient client = new TcpClient("192.168.101.8", 2223);

//2.通过网络流获取数据信息
NetworkStream stream = client.GetStream();

while (true)
{
//手动输入需要发送的信息
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);

//将信息写入网络流
stream.Write(data, 0, data.Length);
}

//关闭流
stream.Close();
client.Close();
Console.ReadKey();
}
}
}

UdpClient

消息接收方

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace _UdpListener
{
class Program
{
static void Main(string[] args)
{
UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.101.8"),2223));

//接收数据
IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udpClient.Receive(ref point);//通过point确定数据来自哪个ip和端口号,并返回接收的数据
string message = Encoding.UTF8.GetString(data);
Console.WriteLine("收到数据: " + message);
udpClient.Close();
Console.ReadKey();
}
}
}

消息发送方

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace _udpListenerClient
{
class Program
{
static void Main(string[] args)
{
UdpClient client = new UdpClient();
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);

client.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.169.101.8"), 2333));
client.Close();
Console.ReadKey();
}
}
}

Difference between TCP and UDP

After seeing TCP and UDP relevant information, and then write the relevant code, we can summarize these two protocols these differences:

Connection

TCP requires connection operation between the client and the server when a connection needs to "three-way handshake", disconnect the need to "four wave", while the UDP protocol is not the process.

Complexity

TCP protocol is relatively complex, which includes fault tolerance mechanisms and congestion handling, officially because of this, the higher the reliability of TCP. While UDP will have a number of simple, opposite, relatively low reliability of UDP.

Transfer mode

TCP transmission, using a stream mode (Stream), and the UDP datagram is used.

Guess you like

Origin www.cnblogs.com/lijianming180/p/12026648.html