C#中Socket通信用法實(shí)例詳解
本文實(shí)例講述了C#中Socket通信用法。分享給大家供大家參考。具體如下:
一、UDP方式:
服務(wù)器端代碼:
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定義一網(wǎng)絡(luò)端點(diǎn)
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定義一個(gè)Socket
newsock.Bind(ipep);//Socket與本地的一個(gè)終結(jié)點(diǎn)相關(guān)聯(lián)
Console.WriteLine("Waiting for a client..");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定義要發(fā)送的計(jì)算機(jī)的地址
EndPoint Remote = (EndPoint)(sender);//
recv = newsock.ReceiveFrom(data, ref Remote);//接受數(shù)據(jù)
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to my test server!";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true)
{
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
客戶端代碼:
void MainInfo()
{
byte[] data = new byte[1024];//定義一個(gè)數(shù)組用來做數(shù)據(jù)的緩沖區(qū)
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.21"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);//將數(shù)據(jù)發(fā)送到指定的終結(jié)點(diǎn)
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受來自服務(wù)器的數(shù)據(jù)
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)//讀取數(shù)據(jù)
{
input = richTextBox1.Text;//從鍵盤讀取數(shù)據(jù)
if (input == "text")//結(jié)束標(biāo)記
{
break;
}
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//將數(shù)據(jù)發(fā)送到指定的終結(jié)點(diǎn)Remote
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);//從Remote接受數(shù)據(jù)
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client");
server.Close();
}
二、TCP方式:
服務(wù)器端代碼:
Socket serverSocket = null;
Thread clientThread = null;
Socket clientSocket = null;
Thread thread = null;
IPAddress ips = null;
PEndPoint ipep = null;
void ServerStart()
{
ips = Dns.GetHostAddresses(Dns.GetHostName())[0];
//創(chuàng)建IPEndPoint實(shí)例
ipep = new IPEndPoint(ips, 9050);
//創(chuàng)建一個(gè)套接字
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//將所創(chuàng)建的套接字與IPEndPoint綁定
serverSocket.Bind(ipep);
//設(shè)置套接字為收聽模式
serverSocket.Listen(20);
while (listenalive)
{
try
{
//在套接字上接收接入的連接
clientSocket = serverSocket.Accept();
clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
clientThread.Start(clientSocket);
}
catch (Exception ex)
{
WriteErrorLog(ex.Message);
serverSocket.Close();
serverSocket = null;
}
}
}
static void ReceiveData(object obj)
{
bool keepalive = true;
Socket s = obj as Socket;
Byte[] buffer = new Byte[1024];
//根據(jù)收聽到的客戶端套接字向客戶端發(fā)送信息
IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
Console.WriteLine("客戶端ip:" + clientep.Address + " 端口:" + clientep.Port);
string welcome = "連接服務(wù)器成功";
buffer = System.Text.Encoding.Unicode.GetBytes(welcome);
//向客戶端發(fā)送“連接服務(wù)器成功”消息
s.Send(buffer, buffer.Length, SocketFlags.None);
buffer = new Byte[1024];
int bufLen = 0;
string content = string.Empty;
while (true)
{
//在套接字上接收客戶端發(fā)送的信息
bufLen = 0;
try
{
bufLen = s.Receive(buffer);
if (bufLen == 0)
{
break;
}
content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen);
}
catch (Exception ex)
{
break; ;
}
}
Send(s, content);
s = null;
buffer = null;
clientep = null;
Thread.CurrentThread.Abort();
}
客戶端代碼:
void Send(string content)
{
byte[] data = new byte[1024];
newclient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
ie = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipadd), port);//服務(wù)器的IP和端口
try
{
//因?yàn)榭蛻舳酥皇怯脕硐蛱囟ǖ姆?wù)器發(fā)送信息,所以不需要綁定本機(jī)的IP和端口。不需要監(jiān)聽。
newclient.Connect(ie);
}
catch (System.Net.Sockets.SocketException e)
{
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
//連接服務(wù)器成功
string stringdata = System.Text.Encoding.Unicode.GetString(data, 0, recv);
if (stringdata == "連接服務(wù)器成功")
{
newclient.Send(System.Text.Encoding.Unicode.GetBytes(content));
newclient.Shutdown(System.Net.Sockets.SocketShutdown.Send);
data = new byte[1024];
recv = newclient.Receive(data);
string result = System.Text.Encoding.Unicode.GetString(data, 0, recv);
newclient.Shutdown(System.Net.Sockets.SocketShutdown.Receive);
newclient.Close();
MessageBox.Show(result);
}
else
{
MessageBox.Show("連接服務(wù)器失敗", "友情提示");
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
上一篇:C#獲取客戶端相關(guān)信息實(shí)例總結(jié)
欄 目:C#教程
下一篇:C#將圖片存放到SQL SERVER數(shù)據(jù)庫(kù)中的方法
本文標(biāo)題:C#中Socket通信用法實(shí)例詳解
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6958.html
您可能感興趣的文章
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并打開的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁(yè)頁(yè)面的方法
- 01-10C#實(shí)現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10Extjs4如何處理后臺(tái)json數(shù)據(jù)中日期和時(shí)間
- 01-10C#中DataGridView常用操作實(shí)例小結(jié)
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10asp.net中XML如何做增刪改查操作
- 01-10C#利用反射技術(shù)實(shí)現(xiàn)去掉按鈕選中時(shí)的邊框效果
- 01-10C#中查找Dictionary中的重復(fù)值的方法
- 01-10C#實(shí)現(xiàn)子窗體與父窗體通信方法實(shí)例總結(jié)


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載


