一、
C# Socket
之TCP&UDP
转:http://www.soaspx.com/dotnet/csharp/csharp_20120718_9423.html
程序员可以通过Socket来发送和接收网络上的数据,可以理解为一个API。
C#中,MS提供了System.Net.Sockets命名空间,里面包含Socket类。
1.
用socket来访问网络。
访问网络的基本条件:a.
确定本机IP和端口号,socket只有与某IP和端口号绑定,才能发挥威力;b.
协议,可以自己定,还有比如UDP和TCP。
下面是访问网络的步骤:
1)
建立一个套接字。
2)
绑定本机IP和端口号。
3)
如果是TCP,由于其是面向连接的,需要Listen()方法监听网络上是否有人给自己发东西;如果是UDP,因为是无连接的,所以来者不拒。
4)
TCP情况下,如果监听到一个连接,就可以使用accept来接收这个连接,然后就可以利用Send/Receive来执行操作了。而UDP,则不需要accept,直接使用SendTo/ReceiveFrom来执行操作。(UDP由于不需要建立连接,所以发送前不知道对方IP和端口号,因此需要指定一个发送的节点才能进行正常发送和接收)
5)
如果不想发送和接收了,就不要浪费资源了,能close就close。
2.
代码实现:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpserver
{
///
/// Class1 的摘要说明。
///
class server
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
int recv;//用于表示客户端发送的信息长度
byte[] data=new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
IPEndPoint ipep=new IPEndPoint(IPAddress.Any,9050);//本机预使用的IP和端口
Socket newsock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
newsock.Bind(ipep);//绑定
newsock.Listen(10);//监听
Console.WriteLine("waiting for a client
");
Socket client=newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
IPEndPoint clientip=(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("connect with client:"+clientip.Address+" at port:"+clientip.Port);
string welcome="welcome here!";
data=Encoding.ASCII.GetBytes(welcome);
client.Send(data,data.Length,SocketFlags.None);//发送信息
while(true)
{//用死循环来不断的从客户端获取信息
data=new byte[1024];
recv=client.Receive(data);
Console.WriteLine("recv="+recv);
if (recv==0)//当信息长度为0,说明客户端连接断开
break;
Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));
client.Send(data,recv,SocketFlags.None);
}
Console.WriteLine("Disconnected from"+clientip.Address);
client.Close();
newsock.Close();
}
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpclient
{
///
/// Class1 的摘要说明。
///
class client
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
byte[] data=new byte[1024];
Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Console.Write("please input the server ip:");
string ipadd=Console.ReadLine();
Console.WriteLine();
Console.Write("please input the server port:");
int port=Convert.ToInt32(Console.ReadLine());
IPEndPoint ie=new IPEndPoint(IPAddress.Parse(ipadd),port);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ie);
}
catch(SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
string stringdata=Encoding.ASCII.GetString(data,0,recv);
Console.WriteLine(stringdata);
while(true)
{
string input=Console.ReadLine();
if(input=="exit")
break;