客戶端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 客戶端
/// </summary>
namespace tcp協議客戶端
{
class Program
{
static void Main(string[] args)
{
//創建一個Socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//發起建立連接的請求
IPAddress iPAddress = IPAddress.Parse("192.168.3.35");//可以字符串轉換成ipaddress的對象
EndPoint point = new IPEndPoint(iPAddress,7788);
tcpClient.Connect(point);//通過ip和端口號定位一個服務器端
//連接成功 接收消息
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);//length表示接收了多少數據
string message = Encoding.UTF8.GetString(data, 0, length);//只把接收到的數據轉化
Console.WriteLine(message);
//--------向服務器端發送消息------------
string message2 = Console.ReadLine();
tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串轉換爲字節數組發送到服務器端
Console.ReadKey();
}
}
}
服務器端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
/// <summary>
/// 服務器端
/// </summary>
namespace tcp協議
{
class Program
{
static void Main(string[] args)
{
// 創建Socket
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//綁定ip和端口號 192.168.3.35
IPAddress iPAddress = new IPAddress(new byte[] { 192,168,3,35 });//ipaddress是對ip和端口進行封裝的類
EndPoint point = new IPEndPoint(iPAddress,7788);// 向系統申請一個可用的ip端口號
tcpServer.Bind(point);
//開始監聽(等待客戶端鏈接)
tcpServer.Listen(100);//最大連接數
Console.WriteLine("開始監聽");
//接收 返回一個clientSocket
Socket clientScocket= tcpServer.Accept();//暫停當前線程,直到一個客戶端連接過來之後進行下面的操作
Console.WriteLine("一個客戶端連接過來");
//向客戶端發送一個返回消息
string message = "hallo 你好";
byte[] data= Encoding.UTF8.GetBytes(message);//對字符串做編碼,等到一個字節數組
clientScocket.Send(data);
Console.WriteLine("向客戶端發送了一條數據");
//-----------------接收服務器端消息-------------------
byte[] data2 = new byte[1024];//傳建一個字節數組接收客戶端發來的消息
int length = clientScocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0, length);//把字節數組轉換爲字符串
Console.WriteLine("接收了一條消息" + message2);
Console.ReadKey();
}
}
}