我搜索了很多,但互联网上的所有例子都是控制台应用程序.我已经尝试使用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#套接字服务器


基础教程推荐
猜你喜欢
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- 实例详解C#实现http不同方法的请求 2022-12-26
- Unity shader实现高斯模糊效果 2023-01-16
- C# 解析XML和反序列化的示例 2023-04-14
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中的Linq to JSON操作详解 2023-06-08
- C#调用摄像头实现拍照功能的示例代码 2023-03-09