using System;
using System.Net;
using System.Net.Sockets;
namespace Socket_Client
{
class Program
{
static void Main(string[] args)
{
//1、建立Socket對象(和服務端進行通信)
Socket ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//2、連接配接伺服器
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.96.19"),8055);
ClientSocket.Connect(endPoint);
byte[] data = new byte[1024];//用于測試
//3、發送
ClientSocket.Send(data);
//4、接收
ClientSocket.Receive(data);
//關閉
//ClientSocket.Close();
}
}
}
服務端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Socket_SeverTcp
{
class Program
{
static void Main(string[] args)
{
//1、建立服務端Socket對象(負責監聽用戶端)
Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = IPAddress.Parse("192.168.96.19");//這邊這個要改成自己的本機IP位址
EndPoint endpoint = new IPEndPoint(ipaddress,8055);
//2、綁定端口
ServerSocket.Bind(endpoint);
Console.WriteLine("... 啟動伺服器成功");
//3、監聽
ServerSocket.Listen(100);//監聽的長度(比如上廁所有5個坑,有20個人,另外15個就要排隊,這裡留了100個坑)
Console.WriteLine("... 開始監聽");
while (true)//死循環,一直執行監聽
{
//4、等待接收用戶端連接配接(傳回用于和用戶端通信的Socket)//從這裡可以看到服務端的兩個Socket都出來了
Socket newSocket = ServerSocket.Accept();
Console.WriteLine("連接配接到一個用戶端:"+newSocket.RemoteEndPoint);
//這是舉例,我們發的是位元組但我們肉眼可見的是字元串,這邊是為了文法對
byte[] data = new byte[1024];
//5、接收消息
newSocket.Receive(data);
//6、發送
newSocket.Send(data);
//7、關閉
//newSocket.Close();
}
}
}
}