我的服务器端程序:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace tcpserver
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
int port = 8000; //定义侦听端口号 private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息
private TcpListener tlTcpListen; //侦听端口号
private bool blistener = true; //设定标示位,判断侦听状态 private NetworkStream nsStream; //创建接收的基本数据流 private StreamReader srRead;
private StreamWriter swWriter;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox2; private TcpClient tcClient ; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
try { tlTcpListen.Stop(); //关闭侦听 nsStream.Close(); srRead.Close();//释放资源
swWriter.Close(); thThreadRead.Abort();//中止线程 } catch{}
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(16, 24);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(432, 124);
this.listBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(176, 160);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "开始服务";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 384);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(464, 22);
this.statusBar1.TabIndex = 2;
this.statusBar1.Text = "statusBar1";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(112, 224);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(136, 21);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(0, 224);
this.label1.Name = "label1";
this.label1.TabIndex = 4;
this.label1.Text = "发送内容:";
//
// button2
//
this.button2.Location = new System.Drawing.Point(304, 224);
this.button2.Name = "button2";
this.button2.TabIndex = 5;
this.button2.Text = "发送";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(464, 406);
this.Controls.Add(this.button2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.button1);
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 Listen ( ) { try { tlTcpListen = new TcpListener(port);//以8000端口号来初始化TcpListener实例 tlTcpListen.Start ( ) ; //开始监听 statusBar1.Text = "正在监听..." ; tcClient = tlTcpListen.AcceptTcpClient(); //通过TCP连接请求 nsStream = tcClient.GetStream(); //获取用以发送、接收数据的网络基础数据流 srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例 swWriter=new StreamWriter(nsStream); statusBar1.Text = "已经连接!"; while( blistener ) //循环侦听 { string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据 if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码 { tlTcpListen.Stop(); //关闭侦听 nsStream.Close(); //释放资源 srRead.Close(); statusBar1.Text = "连接已经关闭!" ; thThreadRead.Abort(); //中止线程 return; } string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间 listBox1.Items.Add ( sTime + " " + sMessage ) ; } } catch ( System.Security.SecurityException ) { MessageBox.Show ( "侦听失败!" , "错误" ) ; } }
private void button1_Click(object sender, System.EventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) );
thThreadRead.Start();//启动线程
button1.Enabled=false; } private void button2_Click(object sender, System.EventArgs e)
{
if (textBox2.Text !="") {
swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据
swWriter.Flush();
} else {
MessageBox.Show("发送信息不能为空!","错误提示!");
}
}
}
}
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace tcpserver
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
int port = 8000; //定义侦听端口号 private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息
private TcpListener tlTcpListen; //侦听端口号
private bool blistener = true; //设定标示位,判断侦听状态 private NetworkStream nsStream; //创建接收的基本数据流 private StreamReader srRead;
private StreamWriter swWriter;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox2; private TcpClient tcClient ; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
try { tlTcpListen.Stop(); //关闭侦听 nsStream.Close(); srRead.Close();//释放资源
swWriter.Close(); thThreadRead.Abort();//中止线程 } catch{}
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(16, 24);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(432, 124);
this.listBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(176, 160);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "开始服务";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 384);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(464, 22);
this.statusBar1.TabIndex = 2;
this.statusBar1.Text = "statusBar1";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(112, 224);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(136, 21);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(0, 224);
this.label1.Name = "label1";
this.label1.TabIndex = 4;
this.label1.Text = "发送内容:";
//
// button2
//
this.button2.Location = new System.Drawing.Point(304, 224);
this.button2.Name = "button2";
this.button2.TabIndex = 5;
this.button2.Text = "发送";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(464, 406);
this.Controls.Add(this.button2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.button1);
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 Listen ( ) { try { tlTcpListen = new TcpListener(port);//以8000端口号来初始化TcpListener实例 tlTcpListen.Start ( ) ; //开始监听 statusBar1.Text = "正在监听..." ; tcClient = tlTcpListen.AcceptTcpClient(); //通过TCP连接请求 nsStream = tcClient.GetStream(); //获取用以发送、接收数据的网络基础数据流 srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例 swWriter=new StreamWriter(nsStream); statusBar1.Text = "已经连接!"; while( blistener ) //循环侦听 { string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据 if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码 { tlTcpListen.Stop(); //关闭侦听 nsStream.Close(); //释放资源 srRead.Close(); statusBar1.Text = "连接已经关闭!" ; thThreadRead.Abort(); //中止线程 return; } string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间 listBox1.Items.Add ( sTime + " " + sMessage ) ; } } catch ( System.Security.SecurityException ) { MessageBox.Show ( "侦听失败!" , "错误" ) ; } }
private void button1_Click(object sender, System.EventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) );
thThreadRead.Start();//启动线程
button1.Enabled=false; } private void button2_Click(object sender, System.EventArgs e)
{
if (textBox2.Text !="") {
swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据
swWriter.Flush();
} else {
MessageBox.Show("发送信息不能为空!","错误提示!");
}
}
}
}
解决方案 »
- WMI如何获取准确的CPU名称
- 高手请进,xml里如何按字符来选节点
- 结贴率一定要高,周末上班的杯具 vs2008 怎么添加win32的DLL呢?
- C#有Vb.net的AndAlso(短路与运算)和OrElse(短路或运算)运算符吗?
- ○○●tabpage加载窗体实例问题
- 如何实现在线下载,没分了大家帮帮忙
- 在vb 6.0中如何获取到webservice传过来的DataSet---急求解决方法
- 好郁闷的问题:我添加WebBrowser控件到工具箱,为什么在工具箱中找不到?
- C#读 Xml文档,用ds.ReadXml(),怎么会产生两个表啊!
- 获取存储过程输出参数值的一个疑问。
- 关于SOCKET的问题,急求
- datagrid绑定关联表的问题
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;namespace tcpclient
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private StreamWriter swWriter; //用以向网络基础数据流传送数据 private NetworkStream nsStream; //创建发送数据的网络基础数据流 private TcpClient tcpClient; private StreamReader sr;
public string recvs; private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.StatusBar statusBar1; private bool tcpConnect = false;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Label label3; //定义标识符,用以表示TCP连接是否建立 /// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if (tcpConnect)
{ swWriter.WriteLine ( "STOP" ) ; //发送控制码 swWriter.Flush (); //刷新当前数据流中的数据
nsStream.Close (); //清除资源 swWriter.Close (); }
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.listBox1 = new System.Windows.Forms.ListBox();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(40, 96);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "连接IP";
//
// label2
//
this.label2.Location = new System.Drawing.Point(40, 136);
this.label2.Name = "label2";
this.label2.TabIndex = 1;
this.label2.Text = "发送内容";
//
// button1
//
this.button1.Location = new System.Drawing.Point(48, 168);
this.button1.Name = "button1";
this.button1.TabIndex = 2;
this.button1.Text = "连接";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(176, 168);
this.button2.Name = "button2";
this.button2.TabIndex = 3;
this.button2.Text = "发送";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(176, 88);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(192, 21);
this.textBox1.TabIndex = 4;
this.textBox1.Text = "textBox1";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(176, 136);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(192, 21);
this.textBox2.TabIndex = 5;
this.textBox2.Text = "textBox2";
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 344);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(520, 22);
this.statusBar1.TabIndex = 6;
this.statusBar1.Text = "statusBar1";
//
// listBox1
//
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(56, 248);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(328, 88);
this.listBox1.TabIndex = 7;
//
// label3
//
this.label3.Location = new System.Drawing.Point(48, 224);
this.label3.Name = "label3";
this.label3.TabIndex = 8;
this.label3.Text = "接收的数据:";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(520, 366);
this.Controls.Add(this.label3);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e)
{
IPAddress ipRemote ; try { ipRemote = IPAddress.Parse ( textBox1.Text ) ; } catch //判断给定的IP地址的合法性 { MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ; return ; } IPHostEntry ipHost ; try { ipHost = Dns.Resolve ( textBox1.Text ) ; } catch //判断IP地址对应主机是否在线 { MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ; return ; } string sHostName = ipHost.HostName ; try { TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请 nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流 swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例
sr=new StreamReader(nsStream);
Thread recvthread=new Thread(new ThreadStart(recvdata));
recvthread.Start(); button1.Enabled = false ; button2.Enabled = true ; tcpConnect = true ; statusBar1.Text = "已经连接!" ; } catch { MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ; return ; }
}
public void recvdata()
{
recvs=sr.ReadLine();
listBox1.Items.Clear();
listBox1.Items.Add(recvs);
} private void button2_Click(object sender, System.EventArgs e)
{
if (textBox2.Text !="") { swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据 swWriter.Flush(); } else { MessageBox.Show("发送信息不能为空!","错误提示!"); } } }
}
客户端向服务器端发送 没有问题。
但是 服务器向客户端发消息,第一次 没有问题,但是 第二次 就不可以了?
请 大家 帮帮忙?
{
recvs=sr.ReadLine();
listBox1.Items.Clear();
listBox1.Items.Add(recvs);
Thread recvthread=new Thread(new ThreadStart(recvdata));
recvthread.Start();
}每次听取的时候都要再打开一个线程继续等待听取. 不然一次就结束了.
{
int port = 2005;
//this.m_ServerIP = Dns.GetHostAddresses(Dns.GetHostName())[0];
//string host = "127.0.0.1";
// string host = Dns.GetHostAddresses(Dns.GetHostName())[0];
// IPAddress ip = IPAddress.Parse(host);
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
s.Bind(ipe);//绑定2005端口
s.Listen(0);//开始监听
//Console.WriteLine("Wait for connect"); Socket temp = s.Accept();//为新建连接创建新的Socket。
//Console.WriteLine("Get a connect");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
//Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
// MessageBox.Show(recvStr);
if (recvStr == "IDC_PAINT")
{
PDC_PRINT();
} if (recvStr == "CLOSE_WINDOWS")
{
close_Windows();
}
string sendStr = "Ok!Client Send Message Sucessful!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回客户端成功信息
temp.Close();
s.Close(); Thread SecThread = new Thread(new ThreadStart(SecThreadProc));
SecThread.Start();
}
客户端:单线程+socket+tcp
另外你上面的程序中多次出现在一个线程中去直接操纵另一个线程的控件的问题,这样是不允许的,容易发生死锁,如果想操纵可以用委托
而且你的服务器端只可以接受一个客户端的连接如果接两个以上的话发送信息客户端没办法收到
谢谢了!