以下是服务器端代码:
[code=C#]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace ChatSampleServer
{
public partial class ServerForm : Form
{
Socket s;
Socket snew;
Thread td;
Thread threadClient;
static int i = 0;
static int port = 2400;
static IPAddress ip = IPAddress.Parse("10.168.0.69");
delegate void SetListBoxText(string text);
IPEndPoint ipe;
public ServerForm()
{
InitializeComponent();
this.btnCutOff.Enabled = false;
} private void btnStartUp_Click(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(ServerStart));
td.Start();
this.btnStartUp.Enabled = false;
this.btnStop.Enabled = true;
SetListbox("Waiting for being connected......");
} private void ServerStart()
{
try
{
ipe = new IPEndPoint(ip, port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 0);
s.Bind(ipe);
s.Listen(10);
while (true)
{
snew = s.Accept();//当程序运行到这里时候是阻塞的,当有新的连接请求时,才往下运行.
SendMessage(snew, "0");//"0"表示服务器已经启动
IPEndPoint ipe1 = (IPEndPoint)snew.RemoteEndPoint;
SetListbox(ipe1.Address.ToString() + " connected.");
i++; threadClient = new Thread(new ThreadStart(ChatForm));
threadClient.Start(); }
}
catch (Exception)
{
//MessageBox.Show("Error2 is:" + ex.Message);
}
}
#region Send message and Get receiving message format
private void SendMessage(Socket s, string sendMessage)
{
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(sendMessage);
try
{
s.Send(bytes, bytes.Length, 0);
}
catch (Exception)
{ MessageBox.Show("服务器已经停止");
}
}
public string GetReceiveMessage(byte[] bytes,int byteCount)
{
return ASCIIEncoding.ASCII.GetString(bytes, 0, byteCount);
}
#endregion
private void ChatForm()
{
byte[] bytes = new byte[1024];
int bytec; while (true)
{
try
{
if (!snew.Connected)
{
return;
}
else
{
bytec = snew.Receive(bytes, bytes.Length, 0);//当程序运行到这里的时候,是阻塞的,直到有新的消息从客户端发过来才往下运行
}
if (bytec <= 0)//如果没有消息发过来,则跳出这个循环,继续上一步的等待
continue;
string receStr = GetReceiveMessage(bytes, bytec);//ASCIIEncoding.ASCII.GetString(bytes, 0, bytec);
SetListbox(receStr);
}
catch (Exception)
{
//MessageBox.Show("Error1:" + ex.Message);
}
}
}
/// <summary>
/// 设置ListBox的文本属性
/// </summary>
/// <param name="receStr">要设置的文本</param>
private void SetListbox(string receStr)
{ if (this.listBox1.InvokeRequired)
{
SetListBoxText tlbt = SetListbox;
this.Invoke(tlbt, new object[] { receStr });
}
else
{
listBox1.Items.Add(receStr);
}
} private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
{
CloseAll();
} private void btnStop_Click(object sender, EventArgs e)
{
i = 0;
btnStartUp.Enabled = true;
btnStop.Enabled = false;
listBox1.Items.Add("Services stop!");
SendMessage(snew, "-1");//"-1"表示服务器已经停止"
CloseAll();
} private void CloseAll()
{
try
{
if (s != null)
{
s.Close();
}
if (snew != null)
{
snew.Shutdown(SocketShutdown.Both);
snew.Close();
}
if (td != null && td.IsAlive)
{
td.Abort();
}
if (threadClient != null && threadClient.IsAlive)
{
threadClient.Abort();
}
}
catch(Exception)
{
//MessageBox.Show("Error3:" + ex.Message);
}
}
}
}
[code=C#]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace ChatSampleServer
{
public partial class ServerForm : Form
{
Socket s;
Socket snew;
Thread td;
Thread threadClient;
static int i = 0;
static int port = 2400;
static IPAddress ip = IPAddress.Parse("10.168.0.69");
delegate void SetListBoxText(string text);
IPEndPoint ipe;
public ServerForm()
{
InitializeComponent();
this.btnCutOff.Enabled = false;
} private void btnStartUp_Click(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(ServerStart));
td.Start();
this.btnStartUp.Enabled = false;
this.btnStop.Enabled = true;
SetListbox("Waiting for being connected......");
} private void ServerStart()
{
try
{
ipe = new IPEndPoint(ip, port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 0);
s.Bind(ipe);
s.Listen(10);
while (true)
{
snew = s.Accept();//当程序运行到这里时候是阻塞的,当有新的连接请求时,才往下运行.
SendMessage(snew, "0");//"0"表示服务器已经启动
IPEndPoint ipe1 = (IPEndPoint)snew.RemoteEndPoint;
SetListbox(ipe1.Address.ToString() + " connected.");
i++; threadClient = new Thread(new ThreadStart(ChatForm));
threadClient.Start(); }
}
catch (Exception)
{
//MessageBox.Show("Error2 is:" + ex.Message);
}
}
#region Send message and Get receiving message format
private void SendMessage(Socket s, string sendMessage)
{
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(sendMessage);
try
{
s.Send(bytes, bytes.Length, 0);
}
catch (Exception)
{ MessageBox.Show("服务器已经停止");
}
}
public string GetReceiveMessage(byte[] bytes,int byteCount)
{
return ASCIIEncoding.ASCII.GetString(bytes, 0, byteCount);
}
#endregion
private void ChatForm()
{
byte[] bytes = new byte[1024];
int bytec; while (true)
{
try
{
if (!snew.Connected)
{
return;
}
else
{
bytec = snew.Receive(bytes, bytes.Length, 0);//当程序运行到这里的时候,是阻塞的,直到有新的消息从客户端发过来才往下运行
}
if (bytec <= 0)//如果没有消息发过来,则跳出这个循环,继续上一步的等待
continue;
string receStr = GetReceiveMessage(bytes, bytec);//ASCIIEncoding.ASCII.GetString(bytes, 0, bytec);
SetListbox(receStr);
}
catch (Exception)
{
//MessageBox.Show("Error1:" + ex.Message);
}
}
}
/// <summary>
/// 设置ListBox的文本属性
/// </summary>
/// <param name="receStr">要设置的文本</param>
private void SetListbox(string receStr)
{ if (this.listBox1.InvokeRequired)
{
SetListBoxText tlbt = SetListbox;
this.Invoke(tlbt, new object[] { receStr });
}
else
{
listBox1.Items.Add(receStr);
}
} private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
{
CloseAll();
} private void btnStop_Click(object sender, EventArgs e)
{
i = 0;
btnStartUp.Enabled = true;
btnStop.Enabled = false;
listBox1.Items.Add("Services stop!");
SendMessage(snew, "-1");//"-1"表示服务器已经停止"
CloseAll();
} private void CloseAll()
{
try
{
if (s != null)
{
s.Close();
}
if (snew != null)
{
snew.Shutdown(SocketShutdown.Both);
snew.Close();
}
if (td != null && td.IsAlive)
{
td.Abort();
}
if (threadClient != null && threadClient.IsAlive)
{
threadClient.Abort();
}
}
catch(Exception)
{
//MessageBox.Show("Error3:" + ex.Message);
}
}
}
}
解决方案 »
- 网页上播放视频问题<基于土-豆的SWF播放器分享功能>
- C#如何利用timer做成倒计时,显示分钟和秒
- 关于用dt 批量插入数据
- winform datagridview 如何增加展开行
- c#怎么做一个多线程,让它空闲等待,直到有消息触发时再执行任务,执行完毕后继续等待
- 往数据库插入不了数据,而且很奇怪,同一个页面,能插入试卷的选择信息,但插入不了考试成绩?我看不出是什么原因,请高手帮帮忙!!!!
- 该错误如何解决?
- 还是这个没解决的老问题,如何在父窗体(MDI)的子窗体中打开父窗体(MDI)的另一个子窗体呢???
- 新手刚学网络编程,想问大家一个问题。
- 如何进行多人协同开发?
- DataGridView列移动后,怎么打印出被移动的值 100分求解
- dropdownlist 的问题
namespace ChatSampleServer
{
partial class ServerForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.btnStartUp = new System.Windows.Forms.Button();
this.btnCutOff = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox1.FormattingEnabled = true;
this.listBox1.HorizontalScrollbar = true;
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(13, 13);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(267, 196);
this.listBox1.TabIndex = 0;
//
// btnStartUp
//
this.btnStartUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnStartUp.Location = new System.Drawing.Point(13, 227);
this.btnStartUp.Name = "btnStartUp";
this.btnStartUp.Size = new System.Drawing.Size(75, 23);
this.btnStartUp.TabIndex = 1;
this.btnStartUp.Text = "启动";
this.btnStartUp.UseVisualStyleBackColor = true;
this.btnStartUp.Click += new System.EventHandler(this.btnStartUp_Click);
//
// btnCutOff
//
this.btnCutOff.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnCutOff.Location = new System.Drawing.Point(106, 227);
this.btnCutOff.Name = "btnCutOff";
this.btnCutOff.Size = new System.Drawing.Size(75, 23);
this.btnCutOff.TabIndex = 2;
this.btnCutOff.Text = "断开";
this.btnCutOff.UseVisualStyleBackColor = true;
//
// btnStop
//
this.btnStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnStop.Location = new System.Drawing.Point(202, 227);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(75, 23);
this.btnStop.TabIndex = 3;
this.btnStop.Text = "停止";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// ServerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnCutOff);
this.Controls.Add(this.btnStartUp);
this.Controls.Add(this.listBox1);
this.Name = "ServerForm";
this.Text = "Server";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ServerForm_FormClosing);
this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button btnStartUp;
private System.Windows.Forms.Button btnCutOff;
private System.Windows.Forms.Button btnStop;
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace ChatSampleClient
{
public partial class ClientForm : Form
{
Socket s;
Thread td;
delegate void SetListBoxText(string text);
delegate void SetButtonAttib(Button btn);
string receString;
public ClientForm()
{
InitializeComponent();
} private void btnConnect_Click(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(ClientStart));
td.Start();
}
#region Send and Receive message format change.
public string GetReceiveMessage(byte[] bytes, int byteCount)
{
return ASCIIEncoding.ASCII.GetString(bytes, 0, byteCount);
}
private void SendMessage(Socket s,string sendMessage)
{
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(sendMessage);
s.Send(bytes, bytes.Length, 0);
}
#endregion
private void ClientStart()
{
try
{
int port = 2400;
IPAddress ip = IPAddress.Parse("10.168.0.69");
IPEndPoint ipe = new IPEndPoint(ip, port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 0);
s.Connect(ipe);
if (s.Connected)
{
SetListbox("Congratulations, you connect!");
}
else
{
MessageBox.Show("连接已经断开");
return;
}
byte[] receByte = new byte[1024];
int bytec;
while (true)
{
bytec = s.Receive(receByte, receByte.Length, 0);
if (bytec <= 0)
continue;
receString = GetReceiveMessage(receByte, bytec);//ASCIIEncoding.ASCII.GetString(receByte, 0, bytec);
if (receString == "-1")
{
SetButtonAtt0(this.btnConnect);//如果已经断开,则设置为True
if (td != null && td.IsAlive)
{
td.Abort();
}
if (s != null)
{
s.Close();
}
return;
}
else if (receString == "0")
{
SetButtonAtt1(this.btnConnect);
}
else
{
SetListbox(receString);
}
}
}
catch (Exception ex)
{
if (ex.Message == "由于目标机器积极拒绝,无法连接。")
{ MessageBox.Show("服务器已经停止!");
}
}
}
#region Set control attributes
private void SetListbox(string receStr)
{ if (this.listBox1.InvokeRequired)
{
SetListBoxText tlbt = SetListbox;
this.Invoke(tlbt, new object[] { receStr });
}
else
{
listBox1.Items.Add(receStr);
}
}
private void SetButtonAtt0(Button btn)
{
if (this.btnConnect.InvokeRequired)
{
SetButtonAttib sba = SetButtonAtt0;
this.Invoke(sba, new object[] { btn });
}
else
{
btn.Enabled = true;
}
}
private void SetButtonAtt1(Button btn)
{
if (this.btnConnect.InvokeRequired)
{
SetButtonAttib sba = SetButtonAtt1;
this.Invoke(sba, new object[] { btn });
}
else
{
btn.Enabled = false;
}
}
#endregion
private void btnSubmit_Click(object sender, EventArgs e)
{
if (s == null)
{
MessageBox.Show("连接已断开");
SetButtonAtt1(btnConnect);
return;
} byte[] bytes = new byte[1024];
if (string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("请输入文字!");
return;
}
string computerName = Dns.GetHostName();
IPAddress[] computerAddr = Dns.GetHostAddresses(computerName);
string computerInfo = computerName + "(" + computerAddr[0].ToString() + "[" + System.DateTime.Now.ToString() + "]" + ")";//客户端信息
string input = textBox1.Text.Trim(); //和发送的实际信息
string clientInfo = computerInfo + ":" + input;
listBox1.Items.Add(computerInfo + ":");
listBox1.Items.Add(input);
SendMessage(s, clientInfo.ToString());
} private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (td != null && td.IsAlive)
{
td.Abort();
}
if (s != null)
{
s.Close();
}
}
}
}
namespace ChatSampleClient
{
partial class ClientForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.btnConnect = new System.Windows.Forms.Button();
this.btnSubmit = new System.Windows.Forms.Button();
this.listBox2 = new System.Windows.Forms.ListBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox1.FormattingEnabled = true;
this.listBox1.HorizontalScrollbar = true;
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(3, 3);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(344, 280);
this.listBox1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(3, 290);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(344, 65);
this.textBox1.TabIndex = 1;
//
// btnConnect
//
this.btnConnect.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnConnect.Location = new System.Drawing.Point(74, 290);
this.btnConnect.Name = "btnConnect";
this.btnConnect.Size = new System.Drawing.Size(75, 23);
this.btnConnect.TabIndex = 2;
this.btnConnect.Text = "连接";
this.btnConnect.UseVisualStyleBackColor = true;
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// btnSubmit
//
this.btnSubmit.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnSubmit.Location = new System.Drawing.Point(74, 332);
this.btnSubmit.Name = "btnSubmit";
this.btnSubmit.Size = new System.Drawing.Size(75, 23);
this.btnSubmit.TabIndex = 3;
this.btnSubmit.Text = "提交";
this.btnSubmit.UseVisualStyleBackColor = true;
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
//
// listBox2
//
this.listBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox2.FormattingEnabled = true;
this.listBox2.HorizontalScrollbar = true;
this.listBox2.ItemHeight = 12;
this.listBox2.Location = new System.Drawing.Point(3, 3);
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(188, 280);
this.listBox2.TabIndex = 4;
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.listBox1);
this.splitContainer1.Panel1.Controls.Add(this.textBox1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.listBox2);
this.splitContainer1.Panel2.Controls.Add(this.btnSubmit);
this.splitContainer1.Panel2.Controls.Add(this.btnConnect);
this.splitContainer1.Size = new System.Drawing.Size(548, 364);
this.splitContainer1.SplitterDistance = 350;
this.splitContainer1.TabIndex = 0;
//
// ClientForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(548, 366);
this.Controls.Add(this.splitContainer1);
this.Name = "ClientForm";
this.Text = "Client";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ClientForm_FormClosing);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Button btnSubmit;
private System.Windows.Forms.ListBox listBox2;
private System.Windows.Forms.SplitContainer splitContainer1;
}
}
目前只是个开头,想完成的功能是:
局域网内的多个主机可以连接到服务器,可以向服务器发送消息,并且消息会显示在自己的ListBox中.
出现的问题是:
多台主机可以连接上服务器,但在发送消息的时,开始的时候,多台主机都可以发,服务器都可以接收并显示到ListBox中.但是发送过一次后,就只有一台主机可以发消息并被服务器接收显示!
不知道出了什么问题,还请大侠们指点一下思路!