網絡通訊C#(TCP)簡單實現通訊


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;//套接字
using System.Threading;//線程
namespace ConsoleApp1
{
/// <summary>
/// 服務器端
/// </summary>
/// <param name="args"></param>
class Sever
{
private Socket _SockSever; //服務器監聽套接字
private bool _IsListenContect=true; // 是否監聽服務器(方便退出)

//構造函數
public Sever()
{
//定義網絡終結點(封裝IP與端口)
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.20.102"),8585);//地址與端口號 ip 127.0.0.1 代表本機
//實例化 定義SockSever套接字 TCP是面向流來傳輸的所以用Stream
_SockSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//服務器端綁定地址
_SockSever.Bind(endPoint);
//開始監聽
_SockSever.Listen(10);//10 表示“監聽隊列”最大長度 等於最多鏈接服務器的數量 起限制的作用
Console.WriteLine("服務器端已啟動");

//檢測客戶端是否連接
try
{
while (_IsListenContect)
{
//Accept 方法 : 接受客戶端的連接方法
//這個方法會阻斷當前的線程
Socket sockMsgSever = _SockSever.Accept();
Console.WriteLine("有一個客戶端連接");

//開啟后台線程,進行客戶端的會話
Thread thClientMsg = new Thread(ClientMsg);

thClientMsg.IsBackground = true; //定義成后台線程
thClientMsg.Name = "thClientMsg";
thClientMsg.Start(sockMsgSever);
}
}
catch (Exception)
{


}
}

public void ClientMsg(object sockMsg)
{
Socket socketMsg= sockMsg as Socket; //通訊Socket
while (true)
{
//准備一個“數據緩存”
byte[] msgArray = new byte[1024 * 1024];//1M空間
//接收客戶端發來的數據,返回數據真實的長度。
int trueClientMsgLength= socketMsg.Receive(msgArray);
//byte數組轉String
string strMsg= Encoding.UTF8.GetString(msgArray, 0, trueClientMsgLength);
//退出
if (strMsg=="退出")
{
break;

}
//顯示消息
Console.WriteLine(strMsg);
}
socketMsg.Shutdown(SocketShutdown.Receive);
socketMsg.Close();
}


static void Main(string[] args)
{
Sever severObj = new Sever();
}
}
}

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;
/// <summary>
/// 客戶端
/// </summary>
namespace ConsoleApp2
{
class Client
{
private Socket _SockClient; //客戶端的通訊套接字
private IPEndPoint secerEndPoint; //連接到服務器IP與端口

public Client()
{
//封裝服務器的IP與端口
secerEndPoint = new IPEndPoint(IPAddress.Parse("192.168.20.102"), 8585);
//建立客戶端Sockt
_SockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

try
{
_SockClient.Connect(secerEndPoint);
}
catch (Exception)
{


}
Console.WriteLine("連接服務器成功");

}
public void SendMsg()
{
while (true)
{
//輸入信息
string strMsg= Console.ReadLine();
//退出
if (strMsg=="退出")
{
break;
}
//字節轉換
byte[] byteArray = Encoding.UTF8.GetBytes(strMsg);
//發送數據
_SockClient.Send(byteArray);

Console.WriteLine("我:"+strMsg);

}
//禁用鏈接
_SockClient.Shutdown(SocketShutdown.Both);
//關閉連接
_SockClient.Close();
}

static void Main(string[] args)
{
Client clientObj = new Client();

clientObj.SendMsg();
}

}
}

 


免責聲明!

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



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