C#实现Socket通信连接(控制台)

服务端

  • 1、创建Socket
  • 2、调用Bind绑定IP地址和端口号
  • 3、调用Listen等待客户端连接
  • 4、调用Accept接受客户端连接
  • 5、在While中回应消息并打印客户端发来的消息
using System;
using System.Net;
using System.Net.Sockets;

namespace Serv
{
    class Program
    {
        const int BUFFER_SIZE = 1024;
        static byte[] readBuff = new byte[BUFFER_SIZE];
        static void Main(string[] args)
        {
            Console.Write("Hello World!!!\n");
            //Socket
            Socket listened = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEp = new IPEndPoint(ipAdr, 1234);
            listened.Bind(ipEp);
            //listen
            listened.Listen(0);
            Console.WriteLine("Server is starting");

            //Accept
            Socket confd = listened.Accept();//阻塞
            Console.WriteLine("server Accept");
            while (true)
            {
                
                
                int count = confd.Receive(readBuff);
                String str = System.Text.Encoding.Default.GetString(readBuff, 0, count);
                Console.WriteLine(str);
                str = "Server:Hello Heiren!!!";
                byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
                confd.Send(bytes);

            }

            
        }
    }
}

客户端

  • 1、创建Socket
  • 2、调用Connect连接服务端
  • 3、在while中发送信息和打印接受的消息
  • 4、当控制台输入exit时,退出循环,关闭连接
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;

namespace Client
{
    class Program
    {
        static Socket socket;
        const int BUFFER_SIZE = 1024;
        static byte[] readBuff = new byte[BUFFER_SIZE];
        public static void Main(string[] args)
        {
            Console.Write("Client Hello World!!!\n");
            socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socket.Connect("127.0.0.1",1234);
            int num = 0;
            while(true)
            {
                String str = "Client:Hello Heiren!!!";
                if (num == 0) num++;
                else str = Console.ReadLine();
                if (str.Equals("exit"))
                    break;
                byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
                socket.Send(bytes);
                int count = socket.Receive(readBuff);
                str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
                Console.WriteLine(str);
                
            }
          
            socket.Close();

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值