我编写了以下程序,假设启动,显示表单并连接到服务器并获取消息。但是,当我开始它没有任何反应?
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();
}
}
}
答案 0 :(得分:2)
您已声明:
private NetClient client;
private NetBuffer buffer;
然而,您的Connect()方法构造新的本地客户端和缓冲区,当方法返回时,它将超出范围。实例的客户端和缓冲区永远不会被初始化,因此在ReceiveMessages()方法中使用时没有任何意义。
答案 1 :(得分:1)
你没有打电话给你的方法。
尝试:
static void Main(string[] args)
{
Form1 form = new Form1();
ReceiveMessages();
// or
Update("Me");
}
表单上有任何按钮吗?有点需要更多信息