基于C#的Socket

      首先从原理上解释一下采用Socket接口的网络通讯,这里以最常用的C/S模式作为范例,首先,服务端有一个进程(或多个进程)在指定的端口等待客户来连接,服务程序等待客户的连接信息,一旦连接上之后,就可以按设计的数据交换方法和


  需要知道的是:Socket类支持两种基本模式:同步和异步。其区别在于:在同步模式中,按块传输,对执行网络操作的函数(如Send和 Receive)的调用一直等到所有内容传送操作完成后才将控制返回给调用程序。在异步模式中,是按位传输,需要指定发送的开始和结束。同步模式是最常用的模式。

 

SocketServer:服务端

 

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace SocketServer
{
    public class Server
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 2000;
                //string host = "127.0.0.1";


                //服务端的IP可以设置成“0”
                string host = "0";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);

 

                //创建一个Socket类
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

 

                //绑定2000端口
                socket.Bind(ipe);

 

                //开始监听
                socket.Listen(0);
                while (true)
                {
                    Console.WriteLine("Wait for connect");

 

                    //为新建连接创建新的Socket。
                    Socket temp = socket.Accept();
                    Console.WriteLine("Get a connect");

                    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);
                    string sendStr = "Ok! Client Send Message Sucessful!";

                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);

 

                    //返回客户端成功信息
                    temp.Send(bs, bs.Length, 0);
                    temp.Close();
                }              
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException:{0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException:{0}", e);
            }
        }
    }
}

 

SocketClient:客户端

 

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace SocketClient
{
    public class Client
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 2000;
                string host = "127.0.0.1";
                //string host = "192.168.6.119";
                IPAddress ip = IPAddress.Parse(host);

 

                //把ip和端口转化为IPEndPoint实例
                IPEndPoint ipe = new IPEndPoint(ip, port);            
              
                for (int i = 0; i < 10; i++)
                {
                    //创建一个Socket
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    Console.WriteLine("Conneting...");

 

                    //连接到服务器
                    socket.Connect(ipe);
                    //string sendStr = "hello!This is a socket test";
                    string sendStr = "Hello!This is a Socket Test!";
                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                    Console.WriteLine("Send Message");

 

                    //发送测试信息
                    socket.Send(bs, bs.Length, 0);
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;

 

                    //从服务器端接受返回信息
                    bytes = socket.Receive(recvBytes, recvBytes.Length, 0);
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

 

                    //显示服务器返回信息
                    Console.WriteLine("Client Get Message:{0}", recvStr);
                    socket.Close();
                }
               
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException:{0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException:{0}", e);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
    }
}

 

 

    上面的例子是用的Socket类,System.Net.Socket命名空间还提供了两个抽象高级类TCPClient和UDPClient和用于通讯流处理的NetWorkStream  

     客户端

TcpClienttcpClient=newTcpCLient(主机IP,端口号);
NetworkStreamns=tcp.Client.GetStream();
  服务端

TcpListenertcpListener=newTcpListener(监听端口);
tcpListener.Start();
TcpClienttcpClient=tcpListener.AcceptTcpClient();
NetworkStreamns=tcpClient.GetStream();
  服务端用TcpListener监听,然后把连接的对象实例化为一个TcpClient,调用TcpClient.GetStream()方法,返回网络流实例化为一个NetworlStream流,下面就是用流的方法进行Send,Receive

  如果是UdpClient的话,就直接UdpClient实例化,然后调用UdpClient的Send和Receive方法,需要注意的事,UdpClient没有返回网络流的方法,就是说没有GetStream方法,所以无法流化,而且使用Udp通信的时候,不要服务器监听。

阅读更多
上一篇C#.net,remoting的简单应用实例
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭