Socket服务器端和客户端源码

socket

server端:

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

namespace Server
{

    class Program
    {

        private static Socket serverSocket = null;


        static void Main(string[] args)
        {
            serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any,9999);

            serverSocket.Bind(endPoint);

            serverSocket.Listen(10);

            Console.WriteLine("start listening...");


           Thread thread = new Thread(listenClientConnect);

            thread.Start();

            while (true) { }


        }
        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private static void listenClientConnect()
        {
            Socket clientSocket = serverSocket.Accept();

            Console.WriteLine("client connect success"+clientSocket.AddressFamily.ToString());

            clientSocket.Send(Encoding.Default.GetBytes("connect server success!"+"ip: "+ clientSocket.AddressFamily));

            Thread thread = new Thread(receiveClientMsg);

            thread.Start(clientSocket);
        }
        /// <summary>
        /// 接收客户端消息
        /// </summary>
        private static void receiveClientMsg(object clientSocket) 
        {
            Socket socket = clientSocket as Socket;

            byte[] buffer = new byte[1024];

            int length = socket.Receive(buffer);

            Console.WriteLine(Encoding.Default.GetString(buffer,0,length));

        }

    }

}

client端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    class Program
    {

        private static Socket clientSocket  = null;

        static void Main(string[] args)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

            clientSocket.Connect(remoteIP);

            Console.WriteLine("connect remote server!");

            byte[] buffer = new byte[1024];

            int length = clientSocket.Receive(buffer);

            Console.WriteLine("receive server msg:" + Encoding.Default.GetString(buffer, 0, length));

            clientSocket.Send(Encoding.Default.GetBytes("i am a client !"));

            while (true) { }

        }


    }
}
运行结果:
socket
如果发现下载不了或者地址失效,请联系客服QQ: 2323178881
找资料 » Socket服务器端和客户端源码

提供最优质的资源集合

立即查看 了解详情