C# Socket TCP简单例子(服务器与客户端通信)

这个例子只是简单实现了如何使用 Socket 类实现面向连接的通信。


注意:此例子的目的只是为了说明用套接字写程序的大概思路,而不是实际项目中的使用程序。在这个例子中,实际上还有很多问题没有解决,如消息边界问题、端口号是否被占用、消息命令的解析问题等。。


下面是两个程序的代码,(两个程序均为控制台程序

先发服务端的(Server)完整代码如下:


引入命名空间:

[csharp] view plain copy print ?
  1. using System.Net.Sockets; 
  2. using System.Net; 
  3. using System.Threading; 
using System.Net.Sockets;
using System.Net;
using System.Threading;

完整代码如下:

[csharp] view plain copy print ?
  1. namespace SocketServer 
  2.     class Program 
  3.     { 
  4.         private staticbyte[] result = newbyte[1024]; 
  5.         private staticint myProt = 8885;   //端口 
  6.         static Socket serverSocket; 
  7.         static void Main(string[] args) 
  8.         { 
  9.             //服务器IP地址 
  10.             IPAddress ip = IPAddress.Parse("127.0.0.1"); 
  11.             serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
  12.             serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口 
  13.             serverSocket.Listen(10);    //设定最多10个排队连接请求 
  14.             Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()); 
  15.             //通过Clientsoket发送数据 
  16.             Thread myThread = new Thread(ListenClientConnect); 
  17.             myThread.Start(); 
  18.             Console.ReadLine(); 
  19.         } 
  20.  
  21.         ///  
  22.         /// 监听客户端连接 
  23.         ///  
  24.         private staticvoid ListenClientConnect() 
  25.         { 
  26.             while (true
  27.             { 
  28.                 Socket clientSocket = serverSocket.Accept(); 
  29.                 clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello")); 
  30.                 Thread receiveThread = new Thread(ReceiveMessage); 
  31.                 receiveThread.Start(clientSocket); 
  32.             } 
  33.         } 
  34.  
  35.         ///  
  36.         /// 接收消息 
  37.         ///  
  38.         ///  
  39.         private staticvoid ReceiveMessage(object clientSocket) 
  40.         { 
  41.             Socket myClientSocket = (Socket)clientSocket; 
  42.             while (true
  43.             { 
  44.                 try 
  45.                 { 
  46.                     //通过clientSocket接收数据 
  47.                     int receiveNumber = myClientSocket.Receive(result); 
  48.                     Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)); 
  49.                 } 
  50.                 catch(Exception ex) 
  51.                 { 
  52.                     Console.WriteLine(ex.Message); 
  53.                     myClientSocket.Shutdown(SocketShutdown.Both); 
  54.                     myClientSocket.Close(); 
  55.                     break
  56.                 } 
  57.             } 
  58.         } 
  59.     } 
namespace SocketServer
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8885;   //端口
        static Socket serverSocket;
        static void Main(string[] args)
        {
            //服务器IP地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口
            serverSocket.Listen(10);    //设定最多10个排队连接请求
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            //通过Clientsoket发送数据
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            Console.ReadLine();
        }

        /// 
        /// 监听客户端连接
        /// 
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }

        /// 
        /// 接收消息
        /// 
        /// 
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
    }
}

以上是服务端(server)的完整代码。


客户端(Client)的完整代码如下:


引入命名空间:

[csharp] view plain copy print ?
  1. using System.Net; 
  2. using System.Net.Sockets; 
  3. using System.Threading; 
using System.Net;
using System.Net.Sockets;
using System.Threading;

完整代码:

[csharp] view plain copy print ?
  1. namespace SocketClient 
  2.     class Program 
  3.     { 
  4.         private staticbyte[] result = newbyte[1024]; 
  5.         static void Main(string[] args) 
  6.         { 
  7.             //设定服务器IP地址 
  8.             IPAddress ip = IPAddress.Parse("127.0.0.1"); 
  9.             Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
  10.             try 
  11.             { 
  12.                 clientSocket.Connect(new IPEndPoint(ip, 8885));//配置服务器IP与端口 
  13.                 Console.WriteLine("连接服务器成功"); 
  14.             } 
  15.             catch 
  16.             { 
  17.                 Console.WriteLine("连接服务器失败,请按回车键退出!"); 
  18.                 return
  19.             } 
  20.             //通过clientSocket接收数据 
  21.             int receiveLength = clientSocket.Receive(result); 
  22.             Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result,0,receiveLength)); 
  23.             //通过 clientSocket 发送数据 
  24.             for (int i = 0; i < 10; i++) 
  25.             { 
  26.                 try 
  27.                 { 
  28.                     Thread.Sleep(1000);    //等待1秒钟 
  29.                     string sendMessage ="client send Message Hellp" + DateTime.Now; 
  30.                     clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage)); 
  31.                     Console.WriteLine("向服务器发送消息:{0}" + sendMessage); 
  32.                 } 
  33.                 catch 
  34.                 { 
  35.                     clientSocket.Shutdown(SocketShutdown.Both); 
  36.                     clientSocket.Close(); 
  37.                     break
  38.                 } 
  39.             } 
  40.             Console.WriteLine("发送完毕,按回车键退出"); 
  41.             Console.ReadLine(); 
  42.         } 
  43.     } 
namespace SocketClient
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static void Main(string[] args)
        {
            //设定服务器IP地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败,请按回车键退出!");
                return;
            }
            //通过clientSocket接收数据
            int receiveLength = clientSocket.Receive(result);
            Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result,0,receiveLength));
            //通过 clientSocket 发送数据
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Thread.Sleep(1000);    //等待1秒钟
                    string sendMessage = "client send Message Hellp" + DateTime.Now;
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                    Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
                }
                catch
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
            Console.WriteLine("发送完毕,按回车键退出");
            Console.ReadLine();
        }
    }
}

编译成功后,先运行 服务端(server),再运行客户端(client)即可达到通信效果。

效果如下图:


该程序已在局域网测试通过。(192.168.X.X)

若编译失败,可到下面的地址下载项目文件:

http://download.csdn.net/source/3465765

你可能感兴趣的:(Socket,Socket)