需要知道的是:Socket 類支持兩種基本模式:同步和異步。其區別在於:在同步模式中,對執行網絡操作的函數(如 Send 和 Receive)的調用一直等到操作完成後才將控制返回給調用程序。在異步模式中,這些調用立即返回。
綜合運用以上闡述的使用Visual C#進行Socket網絡程序開發的知識,下面的程序是一個簡單的Socket通訊實例,client向server發送一段測試字符串,server接收並顯示出來,給予clIEnt成功相應。
//clIEnt端
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace socketsample
{
class Class1
{
static void Main()
{
try
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
c.Connect(ipe);
string sendStr = "hello!This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
c.Send(bs, bs.Length, 0);
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0);
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine(recvStr);
c.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.ReadLine();
}
}
}
//server端
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Project1
{
class Class2
{
static void Main()
{
try
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipe);
s.Listen(0);
Socket temp = s.Accept();
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine(recvStr);
string sendStr = "Ok!Sucess!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);
temp.Shutdown(SocketShutdown.Both);
temp.Close();
s.Shutdown(SocketShutdown.Both);
s.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.ReadLine();
}
}
}
以上程序在VS Express 2005 .Net2.0環境下測試通過。