socket編程的一個簡單一實例
伺服器端C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication3
{
class ProgramServer
{
static void Main(string[] args)
{
while (true) //持續監聽。
{
int port = 2000;
string host = "172.16.4.11";//172.16.4.11要替換為你的IP。
/**/
///建立終結點(EndPoint)
IPAddress ip = IPAddress.Parse(host);//把ip地址字串轉換為IPAddress類型的執行個體
IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的連接埠和ip初始化IPEndPoint類的新執行個體
/**/
///建立socket並開始監聽
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立一個socket對像,如果用udp協議,則要用SocketType.Dgram類型的通訊端
s.Bind(ipe);//綁定EndPoint對像(2000連接埠和ip地址)
s.Listen(0);//開始監聽
Console.WriteLine("等待用戶端串連......");
/**/
///接受到client串連,為此串連建立新的socket,並接受資訊
Socket temp = s.Accept();//為建立串連建立新的socket
Console.WriteLine("建立串連");
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("Server Get Message:{0}", recvStr);//把用戶端傳來的資訊顯示出來
/**/
///給client端返回資訊
string sendStr = Console.ReadLine(); //輸入任意語句,返回給用戶端。
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回資訊給用戶端
temp.Close();
s.Close();//關閉socket。
}
}
}
}
用戶端C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace socket2
{
class ProgramClient
{
static void Main(string[] args)
{
try
{
while (true)
{
int port = 2000;
string host = "172.16.4.11";//172.16.4.11要替換為你的IP。
/**/
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和連接埠轉化為IPEndpoint執行個體
/**/
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立Socket
Console.WriteLine("Conneting...");
sock.Connect(ipe);//串連到伺服器
/**/
///向伺服器發送資訊
//string sendStr = "this is my first socket program";
string sendStr = Console.ReadLine();//輸入任意資訊,發送到伺服器端。
byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字串編碼為位元組
Console.WriteLine("Send Message");
sock.Send(bs, bs.Length, 0);//發送資訊
/**/
///接受從伺服器返回的資訊
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = sock.Receive(recvBytes, recvBytes.Length, 0);//從伺服器端接受返回資訊
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("Client Get Message:{0}", recvStr);//顯示伺服器返回資訊
/**/
///一定記著用完socket後要關閉
sock.Close();
}
}
catch (ArgumentNullException e)
{
Console.WriteLine("argumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
}
Console.WriteLine("Press Enter to Exit");
}
}
}