C# socket(TCP/IP協議)通信
服務端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace socketServer
{
class Program
{
//1、創建一個用於監聽連接的Socket對像;
//2、將服務器的字符串ip地址轉換為網絡地址(IPAddress),端口號為int;
//3、將IP與端口綁定(IPEndPoint);
//4、用socket對像的Bind()方法綁定IPEndPoint;
//5、用socket對像的Listen()方法設置同一時刻最大可連接多少個請求;
//6、socket對像的Accept()方法等待客戶端的連接,連接成功返回通信的socket;
//7、用通信socket的send()方法發送消息給客戶端;
//8、用通信socket的Receive()方法接收客戶端發送的消息;
//private static string net_ip = "192.168.186.4";
private static string net_ip = getIp();
private static string net_port = "8000";
static void Main(string[] args)
{
// 1、創建socket對象
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 2、字符串ip轉網絡ip, 端口號轉int
IPAddress ip = IPAddress.Parse(net_ip);
int port = Convert.ToInt32(net_port);
// 3、綁定ip與端口號
IPEndPoint ipPort = new IPEndPoint(ip, port);
//4、socket對象綁定 IPEndPoint
socketWatch.Bind(ipPort);
//5、設置同一時刻最大可連接多少個請求
socketWatch.Listen(10);
//6、阻塞等待連接
Console.WriteLine("等待客戶端連接中....");
Socket socketObj = socketWatch.Accept();
Console.WriteLine("客戶端: {0} 連接成功", socketObj.RemoteEndPoint);
// 7、發送消息
Console.WriteLine("請輸入需要發送的內容");
string value = Console.ReadLine();
socketObj.Send(Encoding.Default.GetBytes(value));
// 8、接收消息
Console.WriteLine("等待客戶端發送消息...");
byte[] buffer = new byte[1024];
socketObj.Receive(buffer);
Console.WriteLine("接收客戶端發送的內容為: {0}", System.Text.Encoding.Default.GetString(buffer));
Console.ReadKey();
}
// 獲取本機ip地址
private static string getIp()
{
string ip = "";
IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress item in IpEntry.AddressList)
{
if (item.AddressFamily == AddressFamily.InterNetwork)
{
ip = item.ToString();
Console.WriteLine("啟動服務器的ip為: {0} 端口號為{1}", ip, net_port);
}
}
return ip;
}
}
}
客戶端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApp2
{
class Program
{
//1、建立一個Socket對像;
//2、將需要連接的字符串ip地址轉換為網絡地址(IPAddress),端口號為int;
//3、用socket對像的Connect()方法,向服務器發出連接請求;
//4、如果連接成功,就用socket對像的Send()方法向服務器發送信息;
//5、用socket對像的Receive()方法接受服務器發來的信息 ;
//6、斷開連接關閉socket;
static void Main(string[] args)
{
Console.WriteLine("請輸入服務器的ip地址");
string net_ip = Console.ReadLine();
Console.WriteLine("請輸入服務器的端口號");
string net_port = Console.ReadLine();
// 1、創建socket對象
Socket socketObj = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 2、字符串ip轉網絡ip, 端口號轉int
IPAddress ip = IPAddress.Parse(net_ip.Trim());
int port = Convert.ToInt32(net_port.Trim());
// 3、連接服務器
socketObj.Connect(ip, port);
// 4、接收消息
Console.WriteLine("等待服務器發送消息...");
byte[] buffer = new byte[1024];
socketObj.Receive(buffer);
Console.WriteLine("接收客戶端發送的內容為: {0}", System.Text.Encoding.Default.GetString(buffer));
// 5、發送消息
Console.WriteLine("請輸入需要發送的內容");
string value = Console.ReadLine();
socketObj.Send(Encoding.Default.GetBytes(value));
Console.ReadKey();
//// 6、關閉客戶端
//socketObj.Close();
}
}
}