C# socket網絡編程 基於TCP協議


socket 服務器端:

1.創建socket

 Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//三個參數分別為枚舉類型(網絡),Socket類型,協議

2.綁定ip和端口號

IPAddress ipAddress = new IPAddress(new byte[] {192,168,119,1});
EndPoint point =new IPEndPoint(ipAddress,8811);
tcpServer .Bind(point);//綁定方法Bind(),IPEndPoint()封裝ip和端口

3.開始監聽

tcpServer.Listen(100);//參數為最大連接數

4.接收客戶端

Socket clientSocket= tcpServer.Accept();

5.給客戶端發信息

string message = "hello welcome!";
byte[] date = Encoding.UTF8.GetBytes(message);//Encoding()轉碼
clientSocket.Send(date);

6.接收客戶端信息

byte[] date2=new byte[1024];
int length = clientSocket.Receive(date2);
string message2 = Encoding.UTF8.GetString(date2, 0, length);
Console.WriteLine("客戶端發信息過來:"+message2);

代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketServer
{
class Program
{
static void Main(string[] args)
{

Socket tcpServer =new Socket( AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = new IPAddress(new byte[] {192,168,191,1});
EndPoint point =new IPEndPoint(ipAddress,8811);
tcpServer .Bind(point);
tcpServer.Listen(100);
Console.WriteLine("開始監聽");

Socket clientSocket= tcpServer.Accept();
Console.WriteLine("一個客戶端鏈接過來");
string message = "hello welcome!";
byte[] date = Encoding.UTF8.GetBytes(message);
clientSocket.Send(date);

byte[] date2=new byte[1024];
int length = clientSocket.Receive(date2);
string message2 = Encoding.UTF8.GetString(date2, 0, length);
Console.WriteLine("客戶端發信息過來:"+message2);

Console.ReadKey();
}
}
}

socket 客戶端

1.創建socket

2.發起請求

tcpClient.Connect();

3.接收服務器端信息

4.向服務器端發信息

代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketClient
{
class Program
{
static void Main(string[] args)
{
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress=new IPAddress(new byte[]{192,168,191,1});
EndPoint point =new IPEndPoint(ipAddress,8811);
tcpClient.Connect(point);
byte[] date = new byte[1024];
int length= tcpClient.Receive(date);
string message = Encoding.UTF8.GetString(date, 0, length);
Console.WriteLine("服務器端發過來的信息:"+message);

string message2 = Console.ReadLine();
tcpClient.Send(Encoding.UTF8.GetBytes(message2));
Console.ReadKey();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM