IP地址操作類
IPAddress類
在該類中有一個(gè)Parse()方法黍氮,可以把點(diǎn)分的十進(jìn)制IP轉(zhuǎn)化成IPAddress類
示例:
IPAddress address = IPAddress.Parse(192.168.0.1);
IPEndPoint類
IPEndPoint其實(shí)就是一個(gè)IP地址和端口的綁定幢尚,可以代表一個(gè)服務(wù)窿吩,用來Socket通訊
TCP的Scoket編程剂公,主要分兩部分:
一起便、服務(wù)端Socket偵聽:
- 創(chuàng)建IPEndPoint實(shí)例念脯,用于Socket偵聽時(shí)綁定狞洋;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
- 創(chuàng)建套接字實(shí)例
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
這里創(chuàng)建的時(shí)候用ProtocolType.Tcp,表示建立一個(gè)面向連接(TCP)的Socket和二。
- 將所創(chuàng)建的套接字與IPEndPoint綁定
serverSocket.Bind(ipep);
- 設(shè)置套接字為接聽模式
serverSocket.Listen(10);
通過以上四步徘铝,我們已經(jīng)建立了Socket的偵聽模式耳胎,下面我們就來設(shè)置怎么樣獲取客戶Socket連接的實(shí)例惯吕,以及連接后的信息發(fā)送惕它。
在套接字上接收接入的連接
在套接字上接受客戶端發(fā)送的信息和發(fā)送信息
二、服務(wù)端Socket偵聽:
- 創(chuàng)建IPEndPoint實(shí)例和套接字
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- 將套接字連接到遠(yuǎn)程服務(wù)器
try{
clientSocket.Connect(ipep)废登;
}
catch(SocketException ex)
{
MessageBox.Show("connect error:" + ex.Message;)
return;
}
- 接受消息
while (true)
{
int bufLen = 0;
try
{
bufLen = clientSocket.Available;
clientSocket.Receive(data, 0, bufLen, SocketFlags.None);
if (bufLen == 0)
{
continue;
}
}
catch (Exception ex)
{ MessageBox.Show("Receive Error:" + ex.Message);
return;
}
string clientcommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen);
lstClient.Items.Add(clientcommand);
- 發(fā)送信息
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(txtClient.Text);
clientSocket.Send(data, data.Length, SocketFlags.None);
代碼示例:
類 Serv
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace 網(wǎng)絡(luò)連接池
{
public class Serv
{
public Socket listenfd;
public Conn[] conns;//新建連接池?cái)?shù)組
public int maxConn = 50;//最大連接數(shù)
public int NewIndex()
{
if (conns == null)
return -1;//連接池?cái)?shù)組為空時(shí)淹魄,返回負(fù)1
for (int i = 0; i < conns.Length ; i++)
{
if (conns[i] == null)
{
conns[i] = new Conn();//連接池?cái)?shù)組當(dāng)前位置為空時(shí),新建一個(gè)連接池對(duì)象
return i;//返回值為conns數(shù)組的index
}
else if (conns[i].isUse == false)
{
return i;//如果當(dāng)前連接池位置沒有被使用時(shí)堡距,且不為空時(shí)甲锡,返回conns數(shù)組的index
}
}
return -1;
}
public void Start(string host, int port)
{
conns = new Conn[maxConn];//新建連接池?cái)?shù)組,最大連接數(shù)為maxConn
for (int i = 0; i < maxConn; i++)
{
conns[i] = new Conn();
}//新建50個(gè)連接池
listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdr = IPAddress.Parse(host);
IPEndPoint ipEp = new IPEndPoint(ipAdr, port);
listenfd.Bind(ipEp);
listenfd.Listen(maxConn);
listenfd.BeginAccept(AcceptCb, null);
Console.WriteLine("服務(wù)器啟動(dòng)成功");
}
private void AcceptCb(IAsyncResult ar)
{
try
{
Socket socket = listenfd.EndAccept(ar);
int index = NewIndex();
if (index < 0)
{
socket.Close();
Console.Write("警告鏈接已滿");
}
else
{
Conn conn = conns[index];
conn.Init(socket);
string adr = conn.GetAdress();
Console.WriteLine("客戶端鏈接[" + adr + "]conn池ID:" + index);
conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn);
}
listenfd.BeginAccept(AcceptCb, null);
}
catch (Exception e)
{
Console.WriteLine("AcceptCb失敗:" + e.Message);
}
}
private void ReceiveCb(IAsyncResult ar)
{
Conn conn = (Conn) ar.AsyncState;
try
{
int count = conn.socket.EndReceive(ar);
if (count <= 0)
{
Console.WriteLine("收到[" + conn.GetAdress() + "]斷開鏈接");
conn.Close();
return;
}
string str = System.Text.Encoding.UTF8.GetString(conn.readBuff, 0, count);
Console.WriteLine("收到[" + conn.GetAdress() + "]數(shù)據(jù):" + str);
str = conn.GetAdress() + ":" + str;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
for (int i = 0; i < conns.Length; i++)
{
if (conns[i] == null)
continue;
if (!conns[i].isUse)
continue;
Console.WriteLine("將消息傳播給" + conns[i].GetAdress());
conns[i].socket.Send(bytes);
}
conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb,
conn);
}
catch (Exception e)
{
Console.WriteLine("收到["+conn.GetAdress() +"]斷開鏈接");
conn.Close();
}
}
}
}
Conn類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace 網(wǎng)絡(luò)連接池
{
public class Conn
{
public const int BUFFER_SIZE = 1024;
public Socket socket;
public bool isUse = false;
public byte[] readBuff ;
public int buffCount = 0;
public Conn()
{
readBuff = new byte[BUFFER_SIZE];
}
/// <summary>
/// 初始化socket
/// </summary>
/// <param name="socket"></param>
public void Init(Socket socket)
{
this.socket = socket;
isUse = true;
buffCount = 0;
}
public int BuffRemain()
{
return BUFFER_SIZE - buffCount;
}
/// <summary>
/// 獲取連接點(diǎn)的IP地址
/// </summary>
/// <returns></returns>
public string GetAdress()
{
if (!isUse)
return "無法獲取地址";
return socket.RemoteEndPoint.ToString();
}
/// <summary>
/// 斷開鏈接
/// </summary>
public void Close()
{
if (!isUse)
return;
Console.WriteLine("[斷開鏈接]"+GetAdress());
socket.Close();
isUse = false;
}
}
}
Main方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 網(wǎng)絡(luò)連接池
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Serv serv = new Serv();
serv.Start("127.0.0.1",1234);
while (true)
{
string str = Console.ReadLine();
switch (str)
{
case"quit":
return;
}
}
}
}
}
異步客戶端腳本示例
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Mime;
using System.Net.Sockets;
using UnityEngine.UI;
public class netAsyn : MonoBehaviour
{
//服務(wù)器IP和端口
public InputField hostInput;
public InputField portInput;
//顯示客戶端收到的消息
public MediaTypeNames.Text recvText;
public string recvStr;
//顯示客戶端IP和端口
public MediaTypeNames.Text clientText;
//聊天輸入框
public InputField textInput;
//Socket和接收緩沖區(qū)
Socket socket;
const int BUFFER_SIZE = 1024;
public byte[] readBuff = new byte[BUFFER_SIZE];
//因?yàn)橹挥兄骶€程能夠修改UI組件屬性
//因此在Update里更換文本
void Update()
{
recvText.text = recvStr;
}
//連接
public void Connetion()
{
//清理text
recvText.text = "";
//Socket
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//Connect
string host = hostInput.text;
int port = int.Parse(portInput.text);
socket.Connect(host, port);
clientText.text = "客戶端地址 " + socket.LocalEndPoint.ToString();
//Recv
socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCb, null);
}
//接收回調(diào)
private void ReceiveCb(IAsyncResult ar)
{
try
{
//count是接收數(shù)據(jù)的大小
int count = socket.EndReceive(ar);
//數(shù)據(jù)處理
string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
if (recvStr.Length > 300) recvStr = "";
recvStr += str + "\n";
//繼續(xù)接收
socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCb, null);
}
catch (Exception e)
{
recvText.text += "鏈接已斷開";
socket.Close();
}
}
//發(fā)送數(shù)據(jù)
public void Send()
{
string str = textInput.text;
byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
try
{
socket.Send(bytes);
}
catch { }
}
}