服务器端

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

namespace SocketStudy
{
    class Program
    {
        public static void Main(string[] args)
        {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("106.12.219.225");//创建IP地址,可以是本机IP,,可以是127.0.0.1,
            EndPoint endPoint = new IPEndPoint(ip, 4567);//ip地址与端口号的组合,端口号选个大一点的省的被占用
            server.Bind(endPoint);//绑定端口
            server.Listen(100);//设置最大连接数;
            Socket client = server.Accept()//获取客户端的socket,用来与客户端通信
            string message = "hello,我是服务器!";
            byte[] data = Encoding.UTF8.GetBytes(message);//转成能传送的byte类型的数据
            client.Send(data);
            while (true)
            {
                int length = client.Receive(data);
                message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("客户端:" + message);
            }
        }
    }
}

客户端

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SocketStudyClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("106.12.219.225");//创建服务端IP地址
            EndPoint endPoint = new IPEndPoint(ip, 4567);//IP地址和端口号是服务器端的,用来和服务器进行通信
            byte[] data = new byte[1024];
            int length = 0;//设置长度等于零
            string message;
            client.Connect(endPoint);//连接服务器
            length = client.Receive(data);
            message = Encoding.UTF8.GetString(data, 0, length);
            Console.WriteLine(message);
            while (true)
            {
                message = Console.ReadLine();//发送信息
                data = Encoding.UTF8.GetBytes(message);
                client.Send(data);
            }
        }
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注