服务端端口监听

搭建服务端程序,通过 TcpListener 绑定IP与端口,启动端口监听,等待客户端发起TCP连接。提供两种实现版本:控制台程序WinForms窗口程序

核心API说明

  1. IPAddress:代表本机IP地址,IPAddress.Parse("127.0.0.1") 将字符串IP转为对象。
    • 127.0.0.1:本地回环地址,仅本机可访问;若要局域网其他电脑连接,改用内网IP(如192.168.x.x);
    • IPAddress.Any:监听本机所有网卡IP。
  2. TcpListener:TCP服务监听类,构造参数:IP地址 + 端口号
  3. listener.Start()启动监听,调用后服务端开始等待客户端连接。

控制台

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

namespace TalkService
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建IP对象
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            // 创建TCP监听器,监听9500端口
            TcpListener listener = new TcpListener(ip, 9500);
            // 开启监听
            listener.Start();
            Console.WriteLine("开始监听...按E退出");

            ConsoleKeyInfo info;
            do
            {
                info = Console.ReadKey();
            } while (info.Key != ConsoleKey.E);

            listener.Stop(); // 退出时停止监听
        }
    }
}Code language: JavaScript (javascript)

当前代码只启动监听,尚未调用AcceptTcpClient等待客户端接入,只是维持程序不退出。

WinForms版

界面控件:(读者可以往Winform窗体中添加一些控件,用来设置ip 端口,发送的文本信息等)

  • textBoxIP:IP输入框(默认127.0.0.1
  • textBoxPort:端口输入框(默认9500
  • buttonStart:【启动】按钮
  • textBoxInfo:信息显示文本框
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace SocketChatServer
{
    public partial class Form1 : Form
    {
        IPAddress ip;
        TcpListener listener;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            // 解析IP与端口
            ip = IPAddress.Parse(this.textBoxIP.Text);
            int port = Convert.ToInt32(this.textBoxPort.Text);
            listener = new TcpListener(ip, port);

            // 启动监听
            listener.Start();

            // 日志输出
            string log = $"服务器启动 {DateTime.Now.ToShortTimeString()}\r\n";
            this.textBoxInfo.Text = log + this.textBoxInfo.Text;
        }
    }
}Code language: PHP (php)

待解决

  1. UI阻塞大坑
    listener.AcceptTcpClient()阻塞方法,如果直接在按钮点击主线程调用,窗口会卡死。后续需要新开线程/async/await异步等待客户端连接。
  2. 端口占用
    9500端口被其他程序占用时,new TcpListener()启动会抛异常,开发时需要增加try-catch捕获。
  3. 跨主机连通
    绑定127.0.0.1只能本机调试;想要局域网其他电脑连接,IP填写本机局域网IP,同时防火墙放行9500端口。

Previous:
Next:

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注