C#服務器端與客戶端通信(初級)


1、套接字編程

Socket:套接字

套接字是支持TCP/IP協議的網絡通訊的基本操作單元,可以將套接字看做不同主機的進程進行雙向通訊的端點,它構成了單個主機內及整個網絡間的編程界面。

IP地址(Internet Protacol):

是互聯網設備之間傳輸數據的一種協議,IP地址就是給每個連接在因特網的主機(或路由器)分配一個在全世界范圍內唯一的標識符(類似你的家庭住址)。

端口:

標識某台計算機上的進程。

TCP/IP(傳輸控制協議/網際協議):

是一組網絡通訊協議的總稱,它規范了網絡上的所有通訊設備,尤其是一個主機與另一個主機之間的數據交換格式以及傳輸方式

特點:

TCP(傳輸控制協議)  全雙工

基於連接的一種協議

UDP特點:

是一個基於無連接的協議,沒有生成連接的系統延遲,所以速度要比TCP快;

支持一對一、一對多的連接,可以使用廣播的方式多地址的發送;

消耗的網絡帶寬更小;

UDP協議傳輸的數據有消息邊界,而TCP是沒有的

TCP服務器端代碼:

需引用命名空間

using System.Threading;
using System.Net;
using System.Net.Sockets;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Server_Tcp
{
class Server
{
private Socket socket; //服務器監聽套接字
private bool isListen = true;//判斷服務器是否在監聽(目的是為了方便退出)
public Server()
{
//定義網絡終結點(封裝IP和端口)
IPEndPoint endPoint =new IPEndPoint(IPAddress.Parse("127.0.0.1"),9999);
//實例化套接字(監聽套接字)
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
//服務器端綁定地址
socket.Bind(endPoint);
//開始監聽
socket.Listen(10);//10表示“監聽對列”的最大長度
Console.WriteLine("服務器端已經啟動");
try
{
while (isListen)
{
//Accept()接收客戶端的連接
//會阻斷當前線程的進行
Socket acceptSocket = socket.Accept();
Console.WriteLine("有一個客戶端連接。。。。。。");
//開啟一個后台線程,進行客戶端的會話
Thread clientMsg = new Thread(ClientMsg);
clientMsg.IsBackground = true;//設置為后台線程
clientMsg.Name = "clientMsg";//設置線程名字
clientMsg.Start(acceptSocket);
}
}
catch (Exception)
{
}
}
/// <summary>
/// 服務器端和客戶端通訊的后台線程方法
/// </summary>
/// <param name="sockMsg"></param>
public void ClientMsg(object sockMsg)
{
Socket socketMsg = sockMsg as Socket;//通訊Socket
while (true)
{
//准備一個“數據緩存(數組)”
byte[] msg = new byte[1024 * 1024];
//接收客戶端發來的數據,返回數據真實長度
int count = socketMsg.Receive(msg);
//byte數組轉換為string
string str = Encoding.UTF8.GetString(msg, 0, count);
//顯示客戶端發過來的數據
Console.WriteLine("客戶端發過來的數據:"+str);
}

}
static void Main(string[] args)
{
Server server = new Server();
}

 TCP客戶端代碼:

需引用命名空間

using System.Net;
using System.Net.Sockets;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace Client_Tcp
{
class Client
{
private Socket clientSocket;//客戶端通訊套接字
private IPEndPoint serverEndPoiint;//連接到的服務器IP和端口
public Client()
{
serverEndPoiint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9999);
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
clientSocket.Connect(serverEndPoiint);
}
catch (Exception)
{
}
}
public void SendMsg()
{
while (true)
{//輸入數據
string str = Console.ReadLine();
//轉換為字節
byte[] byteArray = Encoding.UTF8.GetBytes(str);
//發送數據
clientSocket.Send(byteArray);
Console.WriteLine("我:"+ str);
}
//關閉連接
clientSocket.Shutdown(SocketShutdown.Both);
//清理連接資源
clientSocket.Close();
}
static void Main(string[] args)
{
Client client = new Client();
client.SendMsg();
}
}
}

UDP接收端代碼:

需引用命名空間

using System.Net;
using System.Net.Sockets;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace Server_Udp
{
class Server
{
private IPEndPoint serverEndPoint;
private Socket serverSocket;
public Server()
{
serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),12345);
serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
serverSocket.Bind(serverEndPoint);
EndPoint ep = (EndPoint)serverEndPoint;
while (true)
{
byte[] byteArray = new byte[1024*1024];
int count = serverSocket.ReceiveFrom(byteArray,ref ep);
string str = Encoding.UTF8.GetString(byteArray,0,count);
Console.WriteLine("客戶端發來的信息:"+str);
}
}
static void Main(string[] args)
{
Server server = new Server();
}
}
}

UDP發送端代碼:

需引用命名空間

using System.Net;
using System.Net.Sockets;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Client_Udp
{
class Client
{
private IPEndPoint clientEndPoint;
private Socket clientrSocket;
public Client()
{
clientEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
clientrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint ep = (EndPoint)clientEndPoint;
while (true)
{
string str = Console.ReadLine();
byte[] byteArray = new byte[1024 * 1024];
byteArray = Encoding.UTF8.GetBytes(str);
clientrSocket.SendTo(byteArray,ep);
Console.WriteLine("我發的信息:" + str);
}
}
static void Main(string[] args)
{
Client client = new Client();
}
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM