带有 Windows 窗体应用程序的 C# 套接字服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10438281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# socket server with windows form application
提问by Teymur Hacizade
I searched a lot but all examples in the internet are console application. I've tried use console application example for windows forms but when I call socket.start form freezes and status changes to (not response). Also I tried multiple threads but it's unsuccessful too. If it is possible please advice me something.
我搜索了很多,但互联网上的所有示例都是控制台应用程序。我已经尝试将控制台应用程序示例用于 Windows 窗体,但是当我调用 socket.start 窗体冻结并且状态更改为(不是响应)时。我也尝试了多个线程,但也不成功。如果可能,请给我一些建议。
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 System.Net;
using System.Net.Sockets;
using System.Threading;
namespace mserver1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ServerClass sc = new ServerClass();
sc.startServer(textBox1, richTextBox1);
}
}
public class ServerClass
{
public void startServer(TextBox tb, RichTextBox rb)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9939);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(20);
rb.Text = rb.Text + "Waiting for client...";
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
rb.Text = rb.Text + "Connected with " + clientep.Address + " at port " + clientep.Port;
string welcome = tb.Text;
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
rb.Text = rb.Text + "Disconnected from" + clientep.Address;
client.Close();
socket.Close();
}
}
}
Thanks.
谢谢。
回答by Sean H
Your application will block until button1_Click returns.
您的应用程序将阻塞,直到 button1_Click 返回。
You need to spawn a worker thread to do your listening. Additionally, you should not pass your controls directly into the worker thread. Rather, you should have a callback that will populate your controls with the data that comes from the socket communications.
您需要生成一个工作线程来进行监听。此外,您不应将控件直接传递给工作线程。相反,您应该有一个回调,它将使用来自套接字通信的数据填充您的控件。
Look up information on the BackgroundWorker. This will get you where you need to go.
查找有关 BackgroundWorker 的信息。这将使您到达需要去的地方。
回答by Vanderley Maia
I had the same problem, follow my solution for the SERVER
我遇到了同样的问题,按照我的 SERVER 解决方案
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.Net;
using System.Net.Sockets;
using System.Threading;
namespace SERVER_WIN
{
public partial class Form1 : Form
{
//Declare and Initialize the IP Adress
static IPAddress ipAd = IPAddress.Parse("10.1.42.31");
//Declare and Initilize the Port Number;
static int PortNumber = 8888;
/* Initializes the Listener */
TcpListener ServerListener = new TcpListener(ipAd, PortNumber);
TcpClient clientSocket = default(TcpClient);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread ThreadingServer = new Thread(StartServer);
ThreadingServer.Start();
}
private void THREAD_MOD(string teste)
{
txtStatus.Text += Environment.NewLine + teste;
}
private void StartServer()
{
Action<string> DelegateTeste_ModifyText = THREAD_MOD;
ServerListener.Start();
Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
clientSocket = ServerListener.AcceptTcpClient();
Invoke(DelegateTeste_ModifyText, "Server ready!");
while (true)
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[20];
networkStream.Read(bytesFrom, 0, 20);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
string serverResponse = "Received!";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch
{
ServerListener.Stop();
ServerListener.Start();
Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
clientSocket = ServerListener.AcceptTcpClient();
Invoke(DelegateTeste_ModifyText, "Server ready!");
}
}
}
}
}
You will need to put in your windows forms just one control TextView, named txtStatus.
您将需要在您的 Windows 窗体中放入一个名为 txtStatus 的控件 TextView。
Client Program:
客户端程序:
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.Net;
using System.Net.Sockets;
using System.IO;
namespace CLIENT_WIN
{
public partial class Form1 : Form
{
TcpClient tcpclnt = new TcpClient();
//Declare and Initialize the IP Adress
IPAddress ipAd = IPAddress.Parse("10.1.42.31");
//Declare and Initilize the Port Number;
int PortNumber = 8888;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Connecting.....");
try
{
tcpclnt.Connect(ipAd, PortNumber);
txtStatus.Text += Environment.NewLine + "Connected";
txtStatus.Text += Environment.NewLine + "Enter the string to be transmitted";
}
catch { }
}
private void btnEnviar_Click(object sender, EventArgs e)
{
String str = txtEnviar.Text + "$";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
txtStatus.Text += Environment.NewLine + "Transmitting...";
//Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string Response = Encoding.ASCII.GetString(bb);
txtStatus.Text += Environment.NewLine + "Response from server: " + Response;
}
}
}
For the Client you will need put some controls; two TextViews (txtStatus and txtEnviar) and a button named btnEnviar, that is it!
对于客户端,您需要放置一些控件;两个 TextViews(txtStatus 和 txtEnviar)和一个名为 btnEnviar 的按钮,就是这样!
You must run at first the Server, than you can run the client, if you need to stop the client, dont worry you can let the Server running.
你必须先运行Server,然后才能运行客户端,如果你需要停止客户端,不用担心你可以让Server运行。

