带有Windows窗体应用程序的C#套接字服务器
发布时间:2020-12-14 04:36:52 所属栏目:Windows 来源:网络整理
导读:我搜索了很多,但互联网上的所有例子都是控制台应用程序.我已经尝试使用 Windows窗体的控制台应用程序示例,但是当我调用socket.start形式冻结和状态更改为(不响应)时.我也尝试了多个线程,但它也不成功.如果有可能请告诉我一些事情. using System;using System
我搜索了很多,但互联网上的所有例子都是控制台应用程序.我已经尝试使用
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上查找信息.这将带您到达您需要去的地方. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- .net – 我应该在Windows消息框中使用警告图标或问号图标吗
- windows-phone-7 – 将存储在隔离存储中的图像绑定到Window
- 限制.net文本框中的行数
- 为什么某些Microsoft Azure服务在Azure Portal中被标记为(经
- GNU CC和Windows
- windows-7 – 无论如何都要阻止Windows 7在更新后执行强制重
- windows – 在DC中以SYSTEM身份运行任务
- 在Windows上从C调用R函数
- windows-phone-7 – 如果我更改现有WP应用程序的ProductID会
- f# – Microsoft.FSharp.Math.Matrix发生了什么?