.net Socket 网络编程(一)

这一篇中实现最简单的socket通信 
在解决方案下新建两个控制台项目(为了方便期间这里使用控制台项目)

服务器端 [ConsoleServer]

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

namespace ConsoleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788);
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(ipEndPoint);
            listener.Listen(50);
            Console.WriteLine("服务启动,开始监听");
            Console.WriteLine("等待客户端连接..."); //如果没有客户端连接会在这里阻塞

            Socket clientSocket = listener.Accept();
            Console.WriteLine("建立连接");
            
            clientSocket.Close();
            Console.WriteLine("关闭客户端连接");
            Console.ReadLine();
        }
    }
}

客户端[ConsoleClient]
为了尽量简单,很多参数都硬编码进去

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

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788);

            ///创建socket并连接到服务器
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.WriteLine("等待连接…");
            serverSocket.Connect(ipEndPoint );//连接到服务器
            Console.WriteLine("已连接");

            serverSocket.Close();
            Console.ReadLine();
        }
    }
}

启动服务器端
会发现输出终止在“等待客户端连接...”
启动客户端
发现正常执行到结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值