我想像服务器发送一些消息,就是一些命令,然后接收从服务器返回的消息!例子:
工作流程 在Dos窗口下输入内容
1.客户端: send -> i 3,abc
2.服务器端:return -> i 3,admin
3.客户端: send -> m 139000100001
4.服务器端:return -> m welcome主要的工作流程就是这样的!我想发消息这块应该是用多线程实现的!
我现在简单的做了一个发消息和收消息的代码!
请师哥们给于指正,我刚做这行不久很多东西都不会!using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net.Sockets;
using System.IO;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpClient c = new TcpClient();
c.Connect("192.168.0.10", 7908); StreamReader sr = new StreamReader(c.GetStream(), Encoding.GetEncoding("GB2312"));
StreamWriter sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); String s; sw.WriteLine("i 3,abc");
sw.Flush(); while ((s = sr.ReadLine()).Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
//System.Console.WriteLine(s);
} System.Console.WriteLine("<<<<<<<");
} public static ArrayList ParseMessage(string msg)
{
//写一个正则表达式
//正则表达式的含义表示字符串中分别包含空格和冒号
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[ |\:|,]");
string[] s = reg.Split(msg); ArrayList arry = new ArrayList();
ConsoleApplication1.CannaString cann = new CannaString();
for (int i = 0; i < s.Length; i++)
{
if (i != s.Length - 1)
{
arry.Add(s[i].ToString());
}
else
{
arry.Add(cann.encode(s[i].ToString()));
}
}
return arry;
}
}
}我这里只是发了一条消息,然后接收的,我想在次输入应该怎么办!我们这里的人交代让我用多线程弄,可是我是真的不会弄!请师哥们见谅!
工作流程 在Dos窗口下输入内容
1.客户端: send -> i 3,abc
2.服务器端:return -> i 3,admin
3.客户端: send -> m 139000100001
4.服务器端:return -> m welcome主要的工作流程就是这样的!我想发消息这块应该是用多线程实现的!
我现在简单的做了一个发消息和收消息的代码!
请师哥们给于指正,我刚做这行不久很多东西都不会!using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net.Sockets;
using System.IO;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpClient c = new TcpClient();
c.Connect("192.168.0.10", 7908); StreamReader sr = new StreamReader(c.GetStream(), Encoding.GetEncoding("GB2312"));
StreamWriter sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); String s; sw.WriteLine("i 3,abc");
sw.Flush(); while ((s = sr.ReadLine()).Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
//System.Console.WriteLine(s);
} System.Console.WriteLine("<<<<<<<");
} public static ArrayList ParseMessage(string msg)
{
//写一个正则表达式
//正则表达式的含义表示字符串中分别包含空格和冒号
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[ |\:|,]");
string[] s = reg.Split(msg); ArrayList arry = new ArrayList();
ConsoleApplication1.CannaString cann = new CannaString();
for (int i = 0; i < s.Length; i++)
{
if (i != s.Length - 1)
{
arry.Add(s[i].ToString());
}
else
{
arry.Add(cann.encode(s[i].ToString()));
}
}
return arry;
}
}
}我这里只是发了一条消息,然后接收的,我想在次输入应该怎么办!我们这里的人交代让我用多线程弄,可是我是真的不会弄!请师哥们见谅!
解决方案 »
- 大家帮我改下这段代码!
- winform链接数据源的小问题
- C#中如何使用别人开发的view类?
- 新手请教一个很简单的问题,请大家帮忙,我没有分了,555555555555
- (winform)能否做到DataGrid只允许修改,不允许增加和删除?
- 求个Winform下WebService对数据库增删改查的列子
- C++项目转换成C#项目
- 有没有大侠做过sqlserver导成access文件?帮帮小D啊,急
- C# execl导入access等待提示窗口
- 如何用js控制TreeView全展开和全收缩
- 谁能提供个关于C#网络编程的教材,最好要中文版的。谢谢
- ====没分了,问个小问题。怎么对Settings.settings执行写操作??===
你说的我还是不太理解,用While怎么做,用线程怎么做! 谢谢!
StreamWriter sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); string str = Console.ReadLine(); while (str != "exit")
{
sw.WriteLine(str);
sw.Flush();
string s = ""; while ((s = sr.ReadLine()).Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
} str = Console.ReadLine();
} System.Console.WriteLine("<<<<<<<");
例如:
在Dos窗口下输入:i 3,abc
返回:i 3,admin
之后光标就不停的闪动,我也无法输入任何字符了!
while ((s = sr.ReadLine()).Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
}
循环完之后,它始终在等,我没法输入下一行!
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net.Sockets;
using System.IO;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpClient c = new TcpClient();
c.Connect("192.168.0.10", 7908); StreamReader sr = new StreamReader(c.GetStream(), Encoding.GetEncoding("GB2312"));
StreamWriter sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); string str = Console.ReadLine(); while (str != "o")
{
sw.WriteLine(str);
sw.Flush();
string s = ""; while ((s = sr.ReadLine()).Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
//System.Console.WriteLine(s);
}
}
System.Console.WriteLine("<<<<<<<");
} public static ArrayList ParseMessage(string msg)
{
//写一个正则表达式
//正则表达式的含义表示字符串中分别包含空格和冒号
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[ |\:|,]");
string[] s = reg.Split(msg); ArrayList arry = new ArrayList();
ConsoleApplication1.CannaString cann = new CannaString();
for (int i = 0; i < s.Length; i++)
{
if (i != s.Length - 1)
{
arry.Add(s[i].ToString());
}
else
{
arry.Add(cann.encode(s[i].ToString()));
}
}
return arry;
}
}
}
while (str != "o")
{
sw.WriteLine(str);
sw.Flush();
while (str.Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
//System.Console.WriteLine(s);
}
}试下,有问题再说...
{
sw.WriteLine(str);
sw.Flush();
while (str.Length > 0)
{
ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
} str = Console.ReadLine();//这句话不能掉了..
}
我今天上班就实验了!还是不行!
师哥可否与我QQ讲解一下:195001405
如果你用while,你的机器cpu消耗很大的.
我的意思就是要做一个多线程,做一个收发消息的工作。例如:
工作流程 在Dos窗口下输入内容
1.客户端: send -> i 3,abc
2.服务器端:return -> i 3,admin
3.客户端: send -> m 139000100001
这个时候服务器返回的可能是多个消息
4.服务器端:return -> m welcome 139000100001
服务器端:return -> m welcome 139000100001
服务器端:return -> m welcome 139000100001
服务器端:return -> m welcome 139000100001
服务器还会继续发送我上一个请求的消息,但是这个时候我客户端会再发一个消息给
服务器,让服务器给返回消息。上一个请求并没有结束。
新:客户端: send -> m 139000100002
新:服务器端:return -> m welcome 139000100002
新:服务器端:return -> m welcome 139000100002
这是第一个请求所接收所有的消息。就是这步:3.客户端: send -> m 139000100001
服务器端:return -> m welcome 139000100001
服务器端:return -> m welcome 139000100001
服务器端:return -> m welcome 139000100001不知道我这样描述,各位师哥明白了吗!
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;namespace ConsoleApplication1
{
class Program
{
static TcpClient c;
static StreamReader sr;
static StreamWriter sw;
static void Main(string[] args)
{
c = new TcpClient();
c.Connect("127.0.0.1", 7908); sr = new StreamReader(c.GetStream(), Encoding.GetEncoding("GB2312"));
sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); Thread td=new Thread(new ThreadStart(Program.ReceiveData));
td.Start();
string str = "a";
while (str != "o")
{
str = Console.ReadLine();
sw.WriteLine(str);
sw.Flush();
System.Console.WriteLine("<<<<<<<");
}
} public static ArrayList ParseMessage(string msg)
{
//写一个正则表达式
//正则表达式的含义表示字符串中分别包含空格和冒号
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[ |\:|,]");
string[] s = reg.Split(msg); ArrayList arry = new ArrayList();
ConsoleApplication1.CannaString cann = new CannaString();
for (int i = 0; i < s.Length; i++)
{
if (i != s.Length - 1)
{
arry.Add(s[i].ToString());
}
else
{
arry.Add(cann.encode(s[i].ToString()));
}
}
return arry;
}
public static void ReceiveData()
{
string s = "";
while (true)
{
while ((s = sr.ReadLine()).Length > 0)
{ ArrayList arry = ParseMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
}
//System.Console.WriteLine(s);
}
} }
}
}
我加你MSN啦!我MSN是:[email protected]
如果我不在发送消息,服务器返回一定数量的消息后就不在发送了。
肯定我一个请求过去,返回是有一定条目的,这个问题我还没考虑那!
光线程和委托我就搞不定了!
这位仁兄的是正解,其实当你的TcpClient连接成功时创建一个接收线程不就结了,只有当对方关闭连接或你自己关闭连接时再入接收线程中退出。
您说的我稍微理解了,确实是应该TcpClient连接成功时创建一个接收线程。
那是否应该在改一下。charles_y(每天上网一小时) 这位师哥的代码那!
应该是你原来的: c.Connect("192.168.0.10", 7908);把它改一下即可。服务器应该不是你做的,所以他返回的东西也不是你能控制的。
这段代码的其他地方不需要改动应该就能满足你的要求
什么事件委托,当这个线程执行的时候执行一个事件,执行事件的内容。我就是
这个接收线程接怎么和这些个事件等等结合起来应用。希望各位师哥帮帮我屡屡
思路,代码指点指点。Thread td=new Thread(new ThreadStart(Program.ReceiveData));new ThreadStart(Program.ReceiveData)这就是一个委托,线程执行时,就是执行的Program.ReceiveData里面的内容..
现在就差一步了,服务器所返回来的所有消息当中我如何能分析,它是
我所发给服务器指令所返回的消息那! 服务器不是我做的,领导指让我做客户端的。
我现在已经了解服务器端发送消息的格式,现在就主要问题就是从客户端发送和接收消息的问题,如何利用多线程的接收。我从客户端发送一个消息,可能从服务器段发回100条消息,我如何接收,我在接收到50条消息的时候,我在此像服务器发送一条消息,服务器又给我发回30条消息,我这新30条消息如何接收。
现在我就是做这个发送和接收的问题。您的例子我做了没问题,就是要知道我怎么对应我发送消息服务器给我返回的消息。
同意!刚才把你的思路跟我们同事一说,我们同事夸我来着,呵呵~
行!就照着师哥的思路我在琢磨琢磨!嘻嘻~
给你一个小列子哦看了肯定有收获的主要就是设计到一个线程lock的问题
可以参考下面代码 :
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Configuration;namespace WindowsApplication2
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components; private LHUM.CallUM trnobj = new LHUM.CallUM(); //WEB服务对象
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.ListBox listBox2;
private string CallID ="";
private ArrayList SendContent=new ArrayList(); //主要存放所有行数
private System.Windows.Forms.Timer timer2;
private ArrayList SendThreads=null;
private int MaxCount = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxCount"]);
private int MaxProcCount = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxProcCount"]);
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.listBox1 = new System.Windows.Forms.ListBox();
this.listBox2 = new System.Windows.Forms.ListBox();
this.timer2 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 4000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// listBox1
//
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(32, 16);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(400, 232);
this.listBox1.TabIndex = 0;
//
// listBox2
//
this.listBox2.ItemHeight = 12;
this.listBox2.Location = new System.Drawing.Point(440, 16);
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(288, 232);
this.listBox2.TabIndex = 1;
//
// timer2
//
this.timer2.Interval = 1000;
this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(736, 266);
this.Controls.Add(this.listBox2);
this.Controls.Add(this.listBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void timer1_Tick(object sender, System.EventArgs e)
{
//count =主要用来控制SMS发送的次数
int count = DataAccess.ExecteRead("select count(id) from umdatabak where MessageType = 'SMS' and ResponseTime>'" + DateTime.Now.ToString("yyyy-MM-dd") + " 00:00'");
if(count>MaxCount)
return; //开启的线程次数一次从数据访问的受影响的条数
DataTable dt = DataAccess.GetSenderInfo(MaxProcCount);
int rowCount=dt.Rows.Count;
if(rowCount>0)
{
//现在把timer1停止,主要来控制线程第二次访问的时间
this.timer1.Stop(); this.SendThreads=new ArrayList();
//该循环把所有的行数加入到ArrayList里面
for(int j= 0;j<rowCount;j++)
{
this.SendContent.Add(dt.Rows[j]);
}
//该循环来根据数据库受影响的行数来开启的多线程
for(int j= 0;j<rowCount;j++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
//把所有的开启的线程加到AllayList里面
this.SendThreads.Add(myThread);
myThread.Start();
}
//线程开启后,然后把第二个timer2开启
this.timer2.Start();
}
}
private void MyThreadProc()
{
//状态
int ResponseStat=1;
string ErrorDesc="";
//获取该行,然后做相应的工作
DataRow row=this.GetSenderContent();
LHUM.UMResult ret=null; if(row!=null)
{
int Id = Convert.ToInt32(row["Id"]); try
{
string MessageType = row["MessageType"].ToString().ToUpper();
MessageType = MessageType.Trim();
string MessageBody = row["MessageBody"].ToString();
string Receiver = row["Receiver"].ToString();
string ValidCode = "lhoa"; switch(MessageType)
{
case "LCS":
ret=this.trnobj.SendLcs(Receiver,MessageBody,ValidCode);
break;
case "SMS":
ret=this.trnobj.SendSms(Receiver,MessageBody,ValidCode,CallID);
break;
case "EMAIL":
ret = this.trnobj.SendMail(Receiver,MessageBody,ValidCode);
break;
default :
throw new Exception("输入错误,没处理");
//ret=this.trnobj.SendMail(Receiver,MessageBody,ValidCode);
// string serverName = "smtp.tom.com";
// string from = @"[email protected]";
// string to = @"[email protected]";
// string MessageText = "我一定要努力 。";
// string subject = "lhoA";
// string username = "[email protected]";
// string userpwd = "WANGHAOWH110";
// if(SendMsg.SendEmail(serverName,from,to,subject,MessageText,username,userpwd))
// {
// this.listBox2.Items.Add(to);
// Application.DoEvents();
// }
break;
} ResponseStat=ret.RTF==true?1:2;
ErrorDesc=ret.RDesc;
//修改信息,把UMDATA表里面的数据修改(主要错误信息)
DataAccess.ExecSender(ResponseStat,ErrorDesc,Id);
//把修改好的UMDATA表里面的数据插入到备份表UMDATABAK里面去
DataAccess.ExecSender(Id);
//删除UMDATA表信息
DataAccess.ExecDel(Id);
//数据更新并移动到备份表,并且删除此数据
}
catch(Exception ee)
{
//写自定义错误信息,把此数据更新并移动到备份表,并且删除此数据
string Error = ee.Message.ToString();
DataAccess.ExecSender(ResponseStat,Error,Id);
DataAccess.ExecSender(Id);
DataAccess.ExecDel(Id);
}
}
}
/// <summary>
/// 线成上锁
/// </summary>
/// <returns></returns>
private DataRow GetSenderContent()
{
lock(this.SendContent)
{
if(this.SendContent.Count>0)
{
DataRow row=(DataRow)this.SendContent[0];
this.SendContent.RemoveAt(0); return row;
}
else
{
return null;
}
}
}
private void timer2_Tick(object sender, System.EventArgs e)
{
//所有线程结束,启动发送进程
bool flag=true;
for(int j= 0;j<this.SendThreads.Count;j++)
{
if(this.SendThreads[j]!=null)
{
Thread t=(Thread)this.SendThreads[j];
if(t.ThreadState!=System.Threading.ThreadState.Stopped)
{
//线程状态没有结束
flag=false;
}
}
}
//线程结束在次开启他timer1来继续第二次多线程
if(flag==true)
{
this.SendThreads=null;
this.timer2.Stop();
this.timer1.Start();
}
}
}
}
{
case "LCS":
ret=this.trnobj.SendLcs(Receiver,MessageBody,ValidCode);
break;
case "SMS":
ret=this.trnobj.SendSms(Receiver,MessageBody,ValidCode,CallID);
break;
case "EMAIL":
ret = this.trnobj.SendMail(Receiver,MessageBody,ValidCode);
break;
default :
}
这个选择语句就是你要实现多线程序的 函数 可以把 这个选择语句改 你要实现多线程的函数。。就Ok 拉。。
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;namespace ThreadExample
{
class Test
{
static TcpClient c;
static StreamReader sr;
static StreamWriter sw;
static ArrayList ReadArry = new ArrayList();
static void Main(string[] args)
{
c = new TcpClient();
c.Connect("127.0.0.1", 7908); sr = new StreamReader(c.GetStream(), Encoding.GetEncoding("GB2312"));
sw = new StreamWriter(c.GetStream(), Encoding.GetEncoding("GB2312")); Thread td = new Thread(new ThreadStart(Test.ReceiveData));
td.Start();
string str = "";
while (str != "o")
{
SendMessage(sw, Console.ReadLine());
System.Console.WriteLine("<<<<<<<");
}
} public static void SendMessage(StreamWriter sw,string Msg)
{
string str = Msg;
sw.WriteLine(str);
sw.Flush(); //ReadArry = new ArrayList();
ReadArry.Add(str);
} public static void GetMessage(string Msg)
{
/*
*如果在存放命令的可变数组里arry里,
* 需要循环取服务器,返回字符串里的首字母,
* 与存放输入命令的可变数字里arry相对应。
*/
for (int j = 0; j < ReadArry.Count; j++)
{
if (ReadArry[j].ToString().Substring(0, 1) == Msg.Substring(0, 1))//判断返回的字符串与输入的命令是否匹配
{
Console.WriteLine("成功");
ReadArry.RemoveAt(j);//如果匹配则把它从数组中删除
}
}
} public static void ReceiveData()
{
string s = "";
while (true)
{
while ((s = sr.ReadLine()).Length > 0)
{
MessageServer m = new MessageServer();
ArrayList arry = m.getMessage(s);
for (int i = 0; i < arry.Count; i++)
{
Console.WriteLine(arry[i].ToString());
GetMessage(arry[i].ToString());
}
//System.Console.WriteLine(s);
}
}
}
}
}