C# 聊天 服务器怎么转发给其他客户端(最好能用集合!) 求~~~
本帖最后由 a398613391 于 2011-11-27 12:24:52 编辑 public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
TcpClient newclient=null ;
Thread nth=null ;
Boolean star = true ;
Thread rd=null ;
NetworkStream ns = null;
BinaryReader nsr = null;
BinaryWriter nsw = null;
public static IPAddress localaddr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localaddr ,8888);
private void button1_Click(object sender, EventArgs e)
{
listener.Start();
textBox1.Text = "服务器启动";
nth = new Thread(new ThreadStart (clientconnect ));
nth.Start();
}
private void clientconnect()
{
int count=1;
while (star)
{
try
{
newclient = listener.AcceptTcpClient();
textBox1.Text = textBox1.Text+"有"+count +"个客户连接了!\n";
}
catch { }
rd = new Thread(new ThreadStart (receivedata ));
rd.Start();
count++;
}
}
private void receivedata()
{
ns = newclient.GetStream();
nsr = new BinaryReader(ns);
nsw = new BinaryWriter(ns);
star = true;
while (star)
{
string str = nsr.ReadString();
textBox1.Text = str;
}
nsr.Close();
nsw.Close();
ns.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(!ns = null;)ns.Close();
star = false;
listener.Stop();
//newclient.Close();
}
}
}
现在能接收多个客户端的链接了 怎么把一个客户端的消息转发给 其他客户端呢 求指点~~~~
[解决办法]
foreach(client in list)
{
//sendMessage
}
[解决办法]
循环发送不就行了,随便你集合还是列表,还是数组
[解决办法]
按你贴的代码,大概修改了下,仅仅只是为了实现楼主的基本需求,异常及其他的问题没有考虑,仅供参考.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
//TcpClient newclient = null;
Thread nth = null;
Boolean star = true;
//Thread rd = null;
//NetworkStream ns = null;
//BinaryReader nsr = null;
//BinaryWriter nsw = null;
public static IPAddress localaddr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localaddr, 8888);
private void button1_Click(object sender, EventArgs e)
{
listener.Start();
Log("服务器启动");
nth = new Thread(new ThreadStart(clientconnect));
nth.Start();
}
private void clientconnect()
{
int count = 1;
while (star)
{
try
{
TcpClient newclient = listener.AcceptTcpClient();
Log( "有" + count + "个客户连接了!");
Thread rd = new Thread(new ParameterizedThreadStart(this.receivedata));
rd.Start(newclient);
count++;
}
catch { }
}
}
private List<MyClient> tcl = new List<MyClient>();
private void Log(string msg)
{
try
{
listBox1.Items.Add(msg);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private void receivedata(object nc)
{
TcpClient newclient = (TcpClient)nc;
NetworkStream ns = newclient.GetStream();
BinaryReader nsr = new BinaryReader(ns);
BinaryWriter nsw = new BinaryWriter(ns);
MyClient c=null;
try
{
c = new MyClient(newclient, nsw);
tcl.Add(c);
star = true;
while (newclient.Connected)
{
string str = nsr.ReadString();
OnBroadCastDelegate del = new OnBroadCastDelegate(this.BroadCast);
del.BeginInvoke(newclient, str, null, null);
}
}
catch (Exception ex)
{
if (c != null && tcl.Contains(c)) tcl.Remove(c);
//System.Diagnostics.Debug.WriteLine(ex.Message);
Log(ex.Message);
}
finally
{
nsr.Close();
nsw.Close();
ns.Close();
}
}
delegate void OnBroadCastDelegate(TcpClient src, string data);
private void BroadCast(TcpClient src, string data)
{
this.listBox1.Items.Add(data);
foreach (MyClient mc in tcl)
{
if(mc.Tc==src) continue;
mc.Writer.Write(data);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//if (ns!=null) ns.Close();
star = false;
tcl.Clear();
listener.Stop();
//newclient.Close();
}
class MyClient
{
public MyClient()
{
}
public MyClient(TcpClient tc, BinaryWriter w)
{
Tc = tc;
Writer = w;
}
public TcpClient Tc = null;
public BinaryWriter Writer = null;
}
}
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;
namespace MyChatRoomClient
{
public partial class FChatClient : Form
{
public FChatClient()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Thread th = null;
//定义一个接收用的缓冲区(2M字节数组)
byte[] arrMsgRec = new byte[1024 * 1024*2];
Socket SocketClient = null;
void ReceiveMsg()
{
while (true)
{
//将接收到的数据存入arrMsgRec数组
int len= SocketClient.Receive(arrMsgRec);
string strMsRec = System.Text.Encoding.UTF8.GetString(arrMsgRec,0,len );
ShowMsg(strMsRec+"\r\n");
}
}
private void btnConnection_Click(object sender, EventArgs e)
{
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketClient.Connect(endpoint);
th = new Thread(ReceiveMsg);
th.Start();
}
void ShowMsg(string msg)
{
txtMessage.AppendText(msg + "/r/n");
}
}
}
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;
namespace MyChatRoomServer
{
public partial class FServer : Form
{
public FServer()
{
InitializeComponent();
//关闭微软对文本框的检查
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Socket SocketWatch = null;
Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
//Socket socketConnection = null;//负责通信的套接字
/// <summary>
/// 监听客户端请求的方法
/// </summary>
void ServerAccept()
{
//持续不断地监听新德客户端的连接请求
while (true)
{
//一旦监听到客户端请求,就返回一个负责和该客户端通信的套接字socketConnection
Socket socketConnection = SocketWatch.Accept();
listBox1.Items.Add(socketConnection.RemoteEndPoint.ToString());
dict.Add(socketConnection.RemoteEndPoint.ToString(), socketConnection);
ShowMsg("客户端连接成功."+socketConnection .RemoteEndPoint .ToString());
}
}
private void btnBeginListen_Click(object sender, EventArgs e)
{
//创建服务端负责监听的套接字,参数(使用IP4寻址协议,使用流式连接,使用TCP协议传送数据)
SocketWatch=new Socket (AddressFamily .InterNetwork ,SocketType .Stream ,ProtocolType.Tcp );
//获得文本框中IP对象
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
//创建包含IP和端口的网络节点对象
IPEndPoint endpoint = new IPEndPoint(address,int.Parse ( txtPort.Text.Trim()));
//将负责监听的套接字绑定到一个IP和端口上
SocketWatch.Bind(endpoint );
//设置监听队列长度
SocketWatch.Listen(10);
//开始监听客户端请求,注意:accept方法,会阻断当前的线程
//Socket socketConnection = SocketWatch.Accept();
Thread th = new Thread(ServerAccept);
//设置为后台线程
th.IsBackground=true;
//开启线程
th.Start();
ShowMsg("服务器监听启动成功 ");
}
void ShowMsg(string msg)
{
txtMessage.AppendText(msg + "\r\n");
}
//发送消息到客户端
private void btnSend_Click(object sender, EventArgs e)
{
string getClient = listBox1.Text;
//拿到文本框内容
string strMsg = txtMsgSend.Text.Trim();
//将要发送的字符串转成utf8对应的字节数组
byte [] arrMsg=System.Text.Encoding.UTF8 .GetBytes(strMsg );
dict[getClient].Send(arrMsg);
// socketConnection.Send(arrMsg);
ShowMsg("发送了数据出去");
}
}
}