C#多线程模拟同时并发如何实现

C#多线程模拟同时并发如何实现,第1张

可参考以下这段代码!

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.Sockets

using System.Net

using System.Threading

using System.IO

namespace Server

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent()

Control.CheckForIllegalCrossThreadCalls = false

}

private void btnStart_Click(object sender, EventArgs e)

{

IPAddress ip = IPAddress.Parse(txtServer.Text)

//网络断点 ip地址和端口号

IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text))

//创建负责监听用的socket

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

try

{

//绑定网络断点

socket.Bind(point)

//监听 10 连接州唯队列的长度

socket.Listen(10)

SetTxt("开始监听")

Thread th = new Thread(Listen)//开启监听的线程

th.IsBackground = true

th.Start(socket)

}

catch (Exception ex)

{

SetTxt(ex.Message)

}

}

Dictionary<string, Socket>dic = new Dictionary<string, Socket>()

void Listen(object o)

{

//负责念迹晌监听用的socket

Socket socket = o as Socket

while (true)

{

try

{

//创建负责通信用的socket

Socket connSocket = socket.Accept()

//获取客户端ip和端口

string ipStr = connSocket.RemoteEndPoint.ToString()

SetTxt(ipStr + ":连接成功")

//填充下拉框

cboUsers.Items.Add(ipStr)

//

dic.Add(ipStr, connSocket)

//开启线程接收消息

Thread th = new Thread(RecMsg)

th.IsBackground = true

th.Start(connSocket)

}

catch (Exception ex)

{

SetTxt(ex.Message)

}

}

}

void RecMsg(object o)

{

Socket connSocket = o as Socket

byte[] buffer = new byte[1024 * 1024 * 5]

while (true)

{

try

{

//count实际收仔锋到的字节个数

int count = connSocket.Receive(buffer)

string ipStr = connSocket.RemoteEndPoint.ToString()

if (count == 0)

{

SetTxt(ipStr + ":断开连接")

connSocket.Shutdown(SocketShutdown.Both)

connSocket.Close()

break

}

string msg = Encoding.UTF8.GetString(buffer, 0, count)

SetTxt(ipStr + ":" + msg)

}

catch (Exception ex)

{

SetTxt(ex.Message)

break

}

}

}

void SetTxt(string t)

{

txtLog.AppendText(t + "\r\n")

}

//发送文字消息

private void btnSend_Click(object sender, EventArgs e)

{

if (cboUsers.SelectedIndex >-1)

{

string key = cboUsers.Text

byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text)

List<byte>list = new List<byte>()

list.Add(1)//协议 1 文字

list.AddRange(buffer)

dic[key].Send(list.ToArray())

}

else

{

MessageBox.Show("请选择客户端")

}

}

//选择路径

private void btnSelect_Click(object sender, EventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog()

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{

txtPath.Text = ofd.FileName

}

}

//发送文件

private void btnSendFile_Click(object sender, EventArgs e)

{

if (cboUsers.SelectedIndex >-1)

{

string key = cboUsers.Text

//dic[key]

//判断文件是否存在

if (txtPath.Text.Length >0)

{

using (FileStream fs = new FileStream(txtPath.Text,FileMode.Open))

{

byte[] buffer = new byte[fs.Length]

fs.Read(buffer, 0, buffer.Length)

List<byte>list = new List<byte>()

list.Add(2 )//协议 2 文件

list.AddRange(buffer)

dic[key].Send(list.ToArray())

}

}

else

{

MessageBox.Show("请选择文件")

}

}

else

{

MessageBox.Show("请选择客户端")

}

}

//震动

private void btnZD_Click(object sender, EventArgs e)

{

if (cboUsers.SelectedIndex >-1)

{

string key = cboUsers.Text

byte[] buffer = new byte[1]

buffer[0] = 3//协议 3 震动

dic[key].Send(buffer)

}

else

{

MessageBox.Show("请选择客户端")

}

}

}

}

首先回答腊亩你的问题:

public int A{ get{ return _a; }set{_a=value}}

这叫封装属性,可以在get或set里对值进行处理,比如这个值不能大于100

可以修改为:

set{if(value<=100){_a=value}} 不用属性的话,轮冲森每个调用_a的地方都要加这段代码,多麻烦

刚好做了一个类似的测试,比你的要求复杂一些,你自己看吧:

// 点击按钮,开始循环测试

private void button1_Click(object sender, EventArgs e)

{

textBox4.Text = string.Empty

string testUrl = txtUrl.Text // 测试地址

string postData = "killId=" + txtKillid.Text // 测试的参数,要post的数据

int threadNum = int.Parse(txtThreadNum.Text) // 发起的线程数,每个线程为一个新的Session,你要无限的话,可以设判锋置为int.MaxValue

int threadTime = 10 // 每个线程跑10次,这是用于要用同一个Session测试10次的情况

for (int i = 0i <threadNumi++)

{

string[] arr = { testUrl, postData, killTime, i.ToString() }

new Thread(Post).Start(arr) // 开始当前线程测试

}

}

public void Post(object arr)

{

string[] para = arr as string[]

string testUrl = para[0]

string postData = para[1]

int killTime = int.Parse(para[2])

int threadNum = int.Parse(para[3])

CookieContainer cookie = new CookieContainer()

while (killTime >0)

{

HttpWebRequest request = WebRequest.Create(testUrl) as HttpWebRequest

request.ContentType = "application/x-www-form-urlencoded"

request.Method = "POST"

request.CookieContainer = cookie

byte[] bodyBytes = Encoding.UTF8.GetBytes(postData)

request.ContentLength = bodyBytes.Length

using (Stream reqStream = request.GetRequestStream())

{

reqStream.Write(bodyBytes, 0, bodyBytes.Length)

reqStream.Flush()

}

request.UserAgent = "Mozilla/4.0 (compatibleMSIE 6.0Windows NT 5.1SV1)"

killTime--

using (WebResponse response = request.GetResponse())

using (Stream sr = response.GetResponseStream())

using (StreamReader reader = new StreamReader(sr))

{

// 把网页返回的内容输出到TextBox中

SetText(textBox4,

threadNum + "," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + ":" + reader.ReadToEnd())

}

cookie = request.CookieContainer

Thread.Sleep(100)

}

}

/// <summary>

/// 用于线程里访问TextBox的线程委托

/// </summary>

/// <param name="tb"></param>

/// <param name="txt"></param>

private delegate void SetTextDelegate(TextBox tb, string txt)

private void SetText(TextBox tb, string txt)

{

if (!tb.InvokeRequired)

{

tb.Text += txt + "\r\n"

}else

{

SetTextDelegate de =SetText

Invoke(de, tb, txt)

//de.Invoke(txt)

}

}

由于停服维护的需求(服务和携圆越来越多的原因),此前编写的shell脚本执行速度缓慢(for循环,这就会很慢),为提高执行速度,参考很多资料,完成此脚本,实现并发执行机制.(当然这是测唤塌试脚本,有需要的同学,拿去改ba改ba,应该就可以用了)

此处脚隐锋本参考了https://www.jb51.net/article/86053.htm


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12512946.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存