简体   繁体   中英

C# Chat Program Lidgren

I wrote the following program that is suppose to start up, show the form and connect to the server and get an messages. However when I start it nothing happens?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lidgren.Network;
using System.Threading;

namespace WindowsGame2
{
    public partial class Form1 : Form
    {
        private NetClient client;
        private NetBuffer buffer;

        public Form1()
        {
            InitializeComponent();
        }

        private void Connect()
        {
            NetConfiguration config = new NetConfiguration("xesh");
            NetClient client = new NetClient(config);

            client.Connect("75.127.105.216", 14242);

            NetBuffer buffer = client.CreateBuffer();
        }

        private void ReceiveMessages()
        {
            Connect();
            bool keepGoing = true;
            while (keepGoing)
            {
                NetMessageType type;
                while (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                        case NetMessageType.DebugMessage:
                            Console.WriteLine(buffer.ReadString());
                            break;

                        case NetMessageType.StatusChanged:
                            Console.WriteLine("New status: " + client.Status + " Reason: " + buffer.ReadString());
                            break;

                        case NetMessageType.Data:
                            break;
                    }
                }
            }
        }

        private void Update(string str)
        {
            ReceiveMessages();
            textBox1.AppendText(str + "\r\n");
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        static void Main(string[] args)
        {
            Form1 form = new Form1();
        }
    }
}

You have declared:

    private NetClient client;        
    private NetBuffer buffer;

However your Connect() method constructs new local client and buffer which will be out of scope when the method returns. The instance's client and buffer never get initialized and there fore will not be meaningful when used in the ReceiveMessages() method.

You aren't calling your methods.

try:

static void Main(string[] args)
{
    Form1 form = new Form1();
    ReceiveMessages();
    // or 
    Update("Me");
}

Do you have any buttons on your form? Kinda need a bit more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM