C#Socket_TCP(客戶端,服務器端通信)
客戶端與服務器通信,通過IP(識別主機)+端口號(識別應用程序)。
IP地址查詢方式:Windows+R鍵,輸入cmd,輸入ipconfig。
端口號:可自行設定,但通常為4位。
服務器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace _021_socket編程_TCP協議
{
class Program
{
static void Main(string[] args)
{
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //TCP協議
//IP+端口號:ip指明與哪個計算機通信,端口號(一般為4位)指明是哪個應用程序
IPAddress ipaddress = new IPAddress(new byte[] { 192, 168, 43, 231 });
EndPoint point = new IPEndPoint(ipaddress, 7788);
tcpServer.Bind(point);
tcpServer.Listen(100);
Console.WriteLine("開始監聽");
Socket clientSocket = tcpServer.Accept();//暫停當前線程,直到有一個客戶端連接過來,之後進行下面的代碼
Console.WriteLine("一個客戶端連接過來了");
string message1 = "hello 歡迎你";
byte[] data1 = Encoding.UTF8.GetBytes(message1);
clientSocket.Send(data1);
Console.WriteLine("向客戶端發送了一條數據");
byte[] data2 = new byte[1024];//創建一個字節數組做容器,去承接客戶端發送過來的數據
int length = clientSocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0, length);//把字節數據轉化成 一個字符串
Console.WriteLine("接收到了一個從客戶端發送過來的消息:" + message2);
Console.ReadKey();
}
}
}
客戶端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace _001_socket編程_tcp協議_客戶端
{
class Program
{
static void Main(string[] args)
{
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = IPAddress.Parse("192.168.43.231");
EndPoint point = new IPEndPoint(ipaddress, 7788);
tcpClient.Connect(point);
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine(message);
//向服務器端發送消息
string message2 = Console.ReadLine();//客戶端輸入數據
tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串轉化成字節數組,然後發送到服務器端
Console.ReadKey();
}
}
}
註意:要實現客戶端與服務器端通信,應分別為其建立工程,並且應該先運行服務器。
C#Socket_TCP(客戶端,服務器端通信)