客戶端與服務器通訊,經過IP(識別主機)+端口號(識別應用程序)。編程
IP地址查詢方式:Windows+R鍵,輸入cmd,輸入ipconfig。數組
端口號:可自行設定,但一般爲4位。服務器
服務器端:socket
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();
}
}
}
tcp
客戶端:spa
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();
}
}
}
注意:要實現客戶端與服務器端通訊,應分別爲其創建工程,而且應該先運行服務器。線程