我想设计一个在局域网上实现通信的程序,有些疑或想请教网络编程高手 老大,TCPListen应该写在一个线程里面,如果有请求,就交给线程处理,只要有一个连接上来,就新建一个线程,线程连接处理完毕就结束该线程,而其他连接可以继续处理这样,你即使是有10万个客户端都没问题 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 不知道你要什么功能,给你个简单的C/S聊天程序研究吧:这是SERVER端:using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.Net;using System.Net.Sockets;using System.Threading;namespace ChatServer{ /// <summary> /// Summary description for Form1. /// </summary> public class ChatServer : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private int listenport = 5555; private TcpListener listener; private System.Windows.Forms.ListBox lbClients; private ArrayList clients; private Thread processor; private Socket clientsocket; private Thread clientservice; public ChatServer() { // // Required for Windows Form Designer support // InitializeComponent(); clients = new ArrayList(); processor = new Thread(new ThreadStart(StartListening)); processor.Start(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lbClients = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // lbClients // this.lbClients.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lbClients.ItemHeight = 16; this.lbClients.Location = new System.Drawing.Point(16, 8); this.lbClients.Name = "lbClients"; this.lbClients.Size = new System.Drawing.Size(264, 228); this.lbClients.TabIndex = 0; // // ChatServer // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.lbClients}); this.Name = "ChatServer"; this.Text = "ChatServer"; this.ResumeLayout(false); } #endregion protected override void OnClosed(EventArgs e) { try { for(int n=0; n<clients.Count; n++) { Client cl = (Client)clients[n]; SendToClient(cl, "QUIT|"); cl.Sock.Close(); cl.CLThread.Abort(); } listener.Stop(); if(processor != null) processor.Abort(); } catch(Exception ex) { Console.WriteLine(ex.ToString() ); } base.OnClosed(e); } private void StartListening() { listener = new TcpListener(listenport); listener.Start(); while (true) { try { Socket s = listener.AcceptSocket(); clientsocket = s; clientservice = new Thread(new ThreadStart(ServiceClient)); clientservice.Start(); } catch(Exception e) { Console.WriteLine(e.ToString() ); } } //listener.Stop(); } private void ServiceClient() { Socket client = clientsocket; bool keepalive = true; while (keepalive) { Byte[] buffer = new Byte[1024]; client.Receive(buffer); string clientcommand = System.Text.Encoding.ASCII.GetString(buffer); string[] tokens = clientcommand.Split(new Char[]{'|'}); Console.WriteLine(clientcommand); if (tokens[0] == "CONN") { for(int n=0; n<clients.Count; n++) { Client cl = (Client)clients[n]; SendToClient(cl, "JOIN|" + tokens[1]); } EndPoint ep = client.RemoteEndPoint; //string add = ep.ToString(); Client c = new Client(tokens[1], ep, clientservice, client); clients.Add(c); string message = "LIST|" + GetChatterList() +"\r\n"; SendToClient(c, message); //lbClients.Items.Add(c.Name + " : " + c.Host.ToString()); lbClients.Items.Add(c); } if (tokens[0] == "CHAT") { for(int n=0; n<clients.Count; n++) { Client cl = (Client)clients[n]; SendToClient(cl, clientcommand); } } if (tokens[0] == "PRIV") { string destclient = tokens[3]; for(int n=0; n<clients.Count; n++) { Client cl = (Client)clients[n]; if(cl.Name.CompareTo(tokens[3]) == 0) SendToClient(cl, clientcommand); if(cl.Name.CompareTo(tokens[1]) == 0) SendToClient(cl, clientcommand); } } if (tokens[0] == "GONE") { int remove = 0; bool found = false; int c = clients.Count; for(int n=0; n<c; n++) { Client cl = (Client)clients[n]; SendToClient(cl, clientcommand); if(cl.Name.CompareTo(tokens[1]) == 0) { remove = n; found = true; lbClients.Items.Remove(cl); //lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString()); } } if(found) clients.RemoveAt(remove); client.Close(); keepalive = false; } } } private void SendToClient(Client cl, string message) { try{ byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message.ToCharArray()); cl.Sock.Send(buffer,buffer.Length,0); } catch(Exception e){ cl.Sock.Close(); cl.CLThread.Abort(); clients.Remove(cl); lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString()); //MessageBox.Show("Could not reach " + cl.Name + " - disconnected","Error", //MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private string GetChatterList() { string chatters = ""; for(int n=0; n<clients.Count; n++) { Client cl = (Client)clients[n]; chatters += cl.Name; chatters += "|"; } chatters.Trim(new char[]{'|'}); return chatters; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new ChatServer()); } }} 这是CLIENT端太长了发不上来呀 这个是c#.net 实例69里的程序。N客户端实时进行聊天,可显示在线人名。 to ikevin(菜无心) :当服务器开始侦听后,当没有任何客户端连接前关闭侦听并退出应用程序,发现有现成阻塞在StartListening函数的Socket s = listener.AcceptSocket();这里,请问该如何解决啊,谢谢! StartListening函数的Socket s = listener.AcceptSocket();不要在主线程中执行侦听,另外开一个线程执行应用程序退出时中止其他线程后在退出主线程 到此处来下载。这里有一个socketagent socket代理。带源码,可供学习使用看明白里机的构造,相信做你想做的局域网通信程序,一定很容易。http://www.pagediy.com/dispbbs.asp?boardID=13&ID=61 啥叫可枚举数据源啊 C#修改信息 咨询:现在的程序开发对数据掌握的要求 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“8856f961-340a-11d0-a96b-00c04fd705a2”。 关于ascii码的问题 C#在不同操作系统的编译出现的问题,急! 不规则界面的一些问题???? 为什么我实例化不了 C# 如何从一个非窗体类中关闭一个窗体? 请问如何修改Carlos H. Perez所写的那个outlookbar的图标? 各位xd,开发文档该怎么写啊?有没有什么例子什么的? 初学.NET,100分求.Net好的相关教材及例程,好的论坛,快
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace ChatServer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class ChatServer : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private int listenport = 5555;
private TcpListener listener;
private System.Windows.Forms.ListBox lbClients;
private ArrayList clients;
private Thread processor;
private Socket clientsocket;
private Thread clientservice; public ChatServer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
clients = new ArrayList();
processor = new Thread(new ThreadStart(StartListening));
processor.Start();
} /// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbClients = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lbClients
//
this.lbClients.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lbClients.ItemHeight = 16;
this.lbClients.Location = new System.Drawing.Point(16, 8);
this.lbClients.Name = "lbClients";
this.lbClients.Size = new System.Drawing.Size(264, 228);
this.lbClients.TabIndex = 0;
//
// ChatServer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lbClients});
this.Name = "ChatServer";
this.Text = "ChatServer";
this.ResumeLayout(false); }
#endregion
protected override void OnClosed(EventArgs e)
{
try
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, "QUIT|");
cl.Sock.Close();
cl.CLThread.Abort();
}
listener.Stop();
if(processor != null)
processor.Abort();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString() );
}
base.OnClosed(e);
}
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
private void ServiceClient()
{
Socket client = clientsocket;
bool keepalive = true; while (keepalive)
{
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer); string[] tokens = clientcommand.Split(new Char[]{'|'});
Console.WriteLine(clientcommand); if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens[1]);
}
EndPoint ep = client.RemoteEndPoint;
//string add = ep.ToString();
Client c = new Client(tokens[1], ep, clientservice, client);
clients.Add(c);
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message); //lbClients.Items.Add(c.Name + " : " + c.Host.ToString());
lbClients.Items.Add(c);
}
if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "PRIV") {
string destclient = tokens[3];
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens[3]) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<c; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}
private void SendToClient(Client cl, string message)
{
try{
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message.ToCharArray());
cl.Sock.Send(buffer,buffer.Length,0);
}
catch(Exception e){
cl.Sock.Close();
cl.CLThread.Abort();
clients.Remove(cl);
lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
//MessageBox.Show("Could not reach " + cl.Name + " - disconnected","Error",
//MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private string GetChatterList()
{
string chatters = "";
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
chatters += cl.Name;
chatters += "|";
}
chatters.Trim(new char[]{'|'});
return chatters;
} /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ChatServer());
}
}
}
当服务器开始侦听后,当没有任何客户端连接前关闭侦听并退出应用程序,发现有现成阻塞在StartListening函数的Socket s = listener.AcceptSocket();这里,请问该如何解决啊,谢谢!
不要在主线程中执行侦听,另外开一个线程执行
应用程序退出时中止其他线程后在退出主线程
看明白里机的构造,相信做你想做的局域网通信程序,一定很容易。http://www.pagediy.com/dispbbs.asp?boardID=13&ID=61