C#中面向連接Socket編程(結合Encoding與線程池)

============================================
============================================
由於是嘗試性的東西,客戶端與服務端寫在同一個類下 生成一個本機通信的exe
============================================
 
using System;//基礎需要
using System.Net;//IPAddress,IPEndPoint需要
using System.Text;//Encoding需要
using System.Threading;//線程需要
using System.Net.Sockets;//Socket需要
class SocketTest
{
public static Socket server=null;
public static Socket client=null;
public static Socket user=null;
public static byte[] clientData=null;//服務端接收client的byte緩衝區
public static byte[] userData=null;//客戶端發送數據byte緩衝區
public static void Main(){
clientData=new byte[128];
userData=new byte[128];//設置緩衝區大小爲128
//IPAddress是C#中對IP的封裝
IPAddress ip0=IPAddress.Parse("127.0.0.1");
//IPEndPoint是C#中對端口與IP的封裝
IPEndPoint endPoint=new IPEndPoint(ip0,8080);
Console.WriteLine(endPoint.ToString());
Console.WriteLine(endPoint.Address);
Console.WriteLine(endPoint.Port);
//服務端ServerSocket,也是一個Socket,但是他要負責執行Accept進行等待
//參數列表爲(網絡類型,Socket數據傳輸方式,協議)
server=new Socket(endPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
//將服務端與端口綁定
server.Bind(endPoint);
//設定允許的排隊隊列大小
server.Listen(100);
//線程列表中加入包含Accept的線程
ThreadPool.QueueUserWorkItem(new WaitCallback(accepting));
//模擬用戶加入的線程
ThreadPool.QueueUserWorkItem(new WaitCallback(userComing));
//模擬服務端接收到的用戶端socket信息,負責接受與發送數據
ThreadPool.QueueUserWorkItem(new WaitCallback(clientWorking));
Console.WriteLine(server.ToString());
//主進程等待1秒,等待以上三個線程執行(unsafe)
Thread.Sleep(1000);
//模擬客戶端發送數據
String tmp="";
while(true){
tmp=Console.ReadLine();
//將客戶端輸入的數據以UTF8的格式轉換成byte
userData=Encoding.UTF8.GetBytes(tmp);
//發送數據(socket發送數據只能以byte數組方式發送)
user.Send(userData);
}
//Console.ReadLine();
}
//模擬服務端與連接到的客戶端交接的管理型client
public static void clientWorking(Object stateInfo){
//實例一個length,存儲接收到的消息長度
int length=0;
while(true){
if(client!=null){
//Receive返回接收到的數據大小
length=client.Receive(clientData,clientData.Length,0);
//將接收到的byte以UTF8格式轉換回字符串,長度爲length,否則轉換後整個緩衝區的
//數據都會出現,干擾
Console.WriteLine(Encoding.UTF8.GetString(clientData,0,length));
}
}
}
//模擬服務端的對應用戶管理socket(unsafe)
public static void accepting(Object stateInfo){
while(true){
client=server.Accept();
break;
}
}
//客戶端(unsafe)
public static void userComing(Object stateInfo){
IPAddress ip1=IPAddress.Parse("127.0.0.1");
IPEndPoint userEndPoint=new IPEndPoint(ip1,8080);
user=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
user.Connect(userEndPoint);
 
}
 
 
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章