C# Socket编程

本文的Socket编程是使用TcpListener和TcpClient来实现的,这两个类是.NET对Socket编程进行的一个封装。

Socket编程基本步骤:

服务器端:

1、新建一个TcpListener对象,并绑定服务器IP地址和端口号;

2、调用TcpListener对象的Start()方法开始监听;

3、接收客户端连接,通过AcceptTcpClient()方法创建一个和客户端通信的TcpClient对象;

4、关闭连接。

客户端:

1、创建一个TcpClient对象;

2、给定服务器IP地址和端口号,通过Connect()方法,请求建立连接;

3、连接建立后,通过Send()和Receive()方法与服务器通信;

4、关闭连接。

如下为一个示例(客户端请求一个文件,服务器响应,发送一个文件):

服务器:

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

namespace SocketServer
{
    class Server
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Server is running...");
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(ip, 8500);

            try
            {
                listener.Start();//开始监听
                Console.WriteLine("Start Listening...");

                int count = 0;
                //循环获取客户端链接
                while (true)
                {
                    TcpClient remoteClient = listener.AcceptTcpClient();
                    Console.WriteLine("Client Connected: {0}<--{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);

                    //获取客户端发送的信息
                    byte[] buffer = new byte[1024];
                    int byteCount = remoteClient.Client.Receive(buffer);
                    string mes = Encoding.Default.GetString(buffer, 0, byteCount);
                    string path = "F:\\" + mes;
                    byte[] messages = File.ReadAllBytes(path);
                    remoteClient.Client.Send(messages);
                    Console.WriteLine("数据发送完毕");
                    remoteClient.Close();//关闭连接

                    ++count;
                    if (count > 100)//处理超过100个连接就关闭服务器
                        return;
                }                
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return;
            }

            //按Q退出
            //Console.WriteLine("\n\n输入\"Q\"键退出");
            //ConsoleKey key;
            //do
            //{
            //    key = Console.ReadKey(true).Key;
            //} while (key != ConsoleKey.Q);
        }
    }
}

客户端:

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

namespace SocketClient
{
    class Client
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Client Running...");
            TcpClient client = new TcpClient();
            try
            {
                client.Connect("localhost", 8500);
                Console.WriteLine("Server Connected: {0}-->{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
                //向客户端发送信息
                byte[] info = Encoding.Default.GetBytes("user1.txt");
                client.Client.Send(info);
                //接受客户端信息
                byte[] buffer = new byte[1024];
                int byteCount = 0;

                while (true)
                {
                    byteCount = client.Client.Receive(buffer);
                    string mes = Encoding.Default.GetString(buffer, 0, byteCount);
                    string path = "F:\\user1Client.txt";
                    File.AppendAllText(path, mes);
                    if (byteCount < 1024) break;
                }
                //关闭连接
                client.Close();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return;
            }

            //按Q退出
            Console.WriteLine("\n\n输入\"Q\"键退出");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
        }
    }
}

 

你可能感兴趣的:(C# Socket编程)