使用TCP的HelloServer
Socket的介紹
Socket類
構造函數定義:
public Socket
{
AddressFamily addressFamily,//制定Socket中的解析地址的尋址方案,ip網絡用addressFaily.InterNetwork
SocketType socketType,//指定Socket類型,TCP用SoocketType.Stream,UDP使用SocketType.Dgram
ProtocolType protocolTyppe//指定Socket類支持的協議。除了常見的ProtocolType.Tcp和ProtocolType.Udp,還有許多,例如IPv6
};
Socket類中的方法:
Bind();
Listen();
Accept();
發送數據Rend();
接受數據Receive();
禁用Socket的發送接受Shutdown();
釋放Socket:Close();
小夥子們,挽起袖子擼代碼(第一個HelloServer程序)
創建控制檯程序——服務端
哦吼~~~~~
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace sockerService
{
class MainClass
{
static void Main(string[] args)
{
//創建socket,包含三個參數、
Socket tcpServer = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//綁定IP
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");//IP
//綁定端口號
IPEndPoint point = new IPEndPoint(ipAddress, 891); //綁定端口
//申請一個可用端口
tcpServer.Bind(point);
//設置最大連接數
tcpServer.Listen(100);
Console.WriteLine("等待連接中......");
//等待用戶連接
Socket clientSocket = tcpServer.Accept();
string message = "hello,歡迎你";
Console.WriteLine("一個用戶已連接......");
//將message轉換成恆字節格式,<UTF8><https://baike.baidu.com/item/UTF-8/481798?fr=aladdin>
Byte[] data = Encoding.UTF8.GetBytes(message);
//將轉換完的字節數組發送到客戶端
clientSocket.Send(data);
//定義第二個數組來接受客戶端發送的消息
Byte[] data2 = new byte[1024];
//記錄接受到信息的長度
int length2 = clientSocket.Receive(data2);
//將接受到的字節文件轉換成string類型·
string message3 = Encoding.UTF8.GetString(data2,0,length2);
Console.WriteLine(message3);
Console.ReadKey();
}
}
}
創建控制檯程序——客戶端
哦吼~
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace sockrtInfo
{
class MainClass
{
public static void Main(string[] args)
{
//1.創建socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//可以吧一個字符串的IP地址轉換成一個IPADDRESS的對象
IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
EndPoint point = new IPEndPoint(ipaddress, 891);
//2/發起建立連接的請求
tcpClient.Connect(point);//通過 IP+端口號定位到一個需要連接的服務器端
byte[] data = new byte[1024];
//這裏傳遞一個BYTE數組,實際上是這個數組來接受數據
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));
tcpClient.Close();
Console.ReadKey();
}
}
}
運行結果
在客戶端控制檯中輸入“哦吼”,服務端會跟着輸出“哦吼”,嘻嘻
到此,就實現了一個最簡單的TCP服務端與客戶端的通信。