【发布时间】:2017-08-12 06:08:58
【问题描述】:
我现在正在尝试制作一个简单的客户端(使用 Windows.Forms),它连接到 Telnet 服务器,并且能够发送和接收数据。
我已成功连接到服务器,但我不知道如何将数据发送回服务器。 (之后我需要弄清楚如何接收响应数据,但我还没有做到这一点。)
这是我当前的代码:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace MUDClient {
public partial class Form1 : Form {
const string SERVER_IP = "166.78.5.182";
const int PORT_NO = 9999;
NetworkStream nwStream;
TcpClient client;
public Form1() {
InitializeComponent();
}
private void btn_connect_Click(object sender, EventArgs e) {
connectToServer();
}
private void btn_disconnect_Click(object sender, EventArgs e) {
client.Close();
nwStream.Close();
rtb_outputWindow.AppendText("\n\nClient: Disconnected.");
}
private void outputWindowTextChanged(object sender, EventArgs e) {
rtb_outputWindow.SelectionStart = rtb_outputWindow.Text.Length;
rtb_outputWindow.ScrollToCaret();
}
private void connectToServer() {
client = new TcpClient(SERVER_IP, PORT_NO);
//client.ReceiveTimeout = 7000;
nwStream = client.GetStream();
new Thread(() => {
Thread.CurrentThread.IsBackground = true;
while (client.Connected) {
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
updateOutputWindow(Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
}
}).Start();
}
private void updateOutputWindow(string text) {
if (InvokeRequired) {
Invoke(new MethodInvoker(delegate () {
updateOutputWindow(text);
}));
}
else {
rtb_outputWindow.AppendText(text);
}
}
private void userSentInput(object sender, KeyEventArgs e) {
RichTextBox inputField = (RichTextBox)sender;
string userInput = inputField.Text.Trim();
if ((e.KeyData == Keys.Enter) && (sender == rtb_inputField)) {
if (nwStream != null) {
if (!string.IsNullOrWhiteSpace(userInput)) {
byte[] bytesToSend = Encoding.ASCII.GetBytes(userInput);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
nwStream.Flush();
rtb_inputField.Clear();
rtb_inputField.Update();
}
}
}
}
}
}
我的程序有两个 RichTextBox(一个用于用户输入,一个用于“服务器输出”,也就是接收的数据)和两个按钮(连接和断开连接)。
单击连接按钮运行 connectToServer() 方法,该方法成功打开服务器和客户端之间的连接。
要发送数据,我想在 RichTextBox (rtb_inputField) 中输入数据,当用户按下 Enter 时,数据就会被发送。这是不起作用的部分。当我按下 Enter 时,似乎什么都没有发生。
编辑:我更新了代码。我在一个新线程中添加了一个连续的连接循环。这是有效的,因为我可以从服务器看到欢迎屏幕。 不过,我仍然无法向服务器发送任何内容。如果我单击“断开连接”按钮,程序将在连续循环中崩溃并出现异常“'System.IO.IOException' 类型的未处理异常”。
【问题讨论】: