我搜索了很多,但互联网上的所有例子都是控制台应用程序.我已经尝试使用Windows窗体的控制台应用程序示例,但是当我调用socket.start形式冻结和状态更改为(不响应)时.我也尝试了多个线程,但它也不成功.如果有可能请告诉...
我搜索了很多,但互联网上的所有例子都是控制台应用程序.我已经尝试使用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();
}
}
}
谢谢.
解决方法:
您的应用程序将阻止,直到button1_Click返回.
您需要生成一个工作线程来进行聆听.此外,您不应将控件直接传递给工作线程.相反,您应该有一个回调,它将使用来自套接字通信的数据填充您的控件.
在BackgroundWorker上查找信息.这将带您到达您需要去的地方.
沃梦达教程
本文标题为:带有Windows窗体应用程序的C#套接字服务器
猜你喜欢
- Oracle中for循环的使用方法 2023-07-04
- user32.dll 函数说明小结 2022-12-26
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- c# 模拟线性回归的示例 2023-03-14
- Unity Shader实现模糊效果 2023-04-27
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- 如何使用C# 捕获进程输出 2023-03-10
- .NET CORE DI 依赖注入 2023-09-27
- Unity3D实现渐变颜色效果 2023-01-16