C#学习日志SocketServer

2019年4月26日 0 条评论 20 次阅读 0 人点赞

C# Socket编程Server实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace SocketTest
{

    class Program
    {
        private static byte[] result = new byte[1024];
        private static Socket serverSocket;
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip,123));
            serverSocket.Listen(5);
            Thread thread = new Thread(ListenClientConnect);
            thread.Start();
            Console.ReadKey();
        }

        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 (myClientSocket.Connected)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveNumber = myClientSocket.Receive(result);
                    if (receiveNumber != 0)
                    {
                        Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                    }
                    else
                    {
                        myClientSocket.Close();
                    }
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
            Console.WriteLine("客户端退出");
        }
    }



}

月下

我想要的,从始至终,不过一个你罢了。

文章评论(0)

你必须 登录 才能发表评论