我正开始构建小型TCP Server。
现在,我被两个事件/功能之间的通信所困扰。 我现在可以在Threads上使用它。
但是如何关闭线程并停止服务器? 它说它不知道Button_stop事件中的客户端和服务器。
“服务器”中的代码是Microsoft的示例代码,但是可以。
我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace MTTCP
{
public partial class Form1 : Form
{
//Declare Thread
Thread Server_Thread;
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
//Start Backround Server Thread
Server_Thread = new Thread(Server);
Server_Thread.Start();
}
//Backround Server
private void Server()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 80.
Int32 port = 80;
IPAddress localAddr = IPAddress.Parse("192.168.0.123");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
//Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
//Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
//Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
//Backround Server Ende
}
private void Stop_Click(object sender, EventArgs e)
{
//Here i want to stop the Thread an determine the Server
client.Close(); //Does not work, doesnt know client
server.Stop(); //Does not work, doesnt know server
}
}
}
问候 NetflixAndChill
答案 0 :(得分:4)
似乎您收到“客户端和服务器在当前上下文中不存在”错误。 您必须将“服务器”和“客户端”变量的范围更改为类级别,才能在Stop_Click事件处理程序中访问它们。
关于, 迪列普。