简单Socket问题:服务器接受客户端信息后如何发送给连接此服务器的所有客户端呢?我做的是一个服务器对多个客户端的,当客户端发送给服务器时,服务器接受并发送给客户端,只是点对点的,就是哪个客户端发送给服务器,服务器就返回给哪个客户端,我的要求是当一个客户端发送给服务器时,服务器发送给连接此服务器的所有客户端,怎么解决?
遍历线程吗?
遍历线程吗?
解决方案 »
- Windows Phone开发的牛人指点
- 网上搜不出答案的问题:System.InvalidOperationException: This document already has a 'Docume
- 关于Remoting入门,关于引用同一个dll的疑惑
- 并非所有的代码都有返回值
- dataset 中两个table 合并 一个table 只有前一个table 中的两行
- asp.net中,static变量是每个client使用一个,还是整个站点的所有用户共享一个变量
- 我作了一个小的WinForm控件(dll),我如何设置它的图标呢?也就是加到工具箱中显示的图标,请高手指点?
- 有谁知道web服务引用超时的解决方法 ,好像是win2003的问题
- 一个winfrom运行两个Timer
- *******DataSet.WriteXML("c:\download\aaa.xml")*********为何老保错?
- 从数组中取一段数据.
- 为什么139邮箱没有发送成功!
//界面上的按钮手动开启Socket监听
private void button1_Click(object sender, EventArgs e)
{
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName); //得到主机IP
string strIPAddr = IpEntry.AddressList[0].ToString();
IPAddress ip = IPAddress.Parse(strIPAddr); //把ip地址字符串转换为IPAddress
IPEndPoint ipep = new IPEndPoint(ip, 11000); //用指定的端口和ip newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);//绑定
newsock.Listen(10);//监听
while (true)
{
try
{
//当有可用的客户端连接尝试时执行,并返回一个新的socket
Socket client = newsock.Accept(); //创建消息服务线程对象,并把连接socket赋于ClientThread
ClientThread newclient = new ClientThread(client); ThreadPool.QueueUserWorkItem(new WaitCallback(newclient.ClientServer));
}
catch
{
//连接中断或者连接失败
}
}
}//此处是一个类
class ClientThread
{ Encoding encoding = Encoding.GetEncoding("GB2312"); //解码器(可以用于汉字)
private Socket client;
private string data = null;
private byte[] receiveBytes = new byte[1024];//服务器端设置缓冲区
private int recCount; //传递连接socket
public ClientThread(Socket ClientSocket)
{
this.client = ClientSocket;
} //数据处理接口
public void ClientServer(object a)
{ try
{
while (true)
{
recCount = client.Receive(receiveBytes, receiveBytes.Length, 0);//从客户端接收信息
if (recCount != 0)//当服务器端的缓冲区接收到的信息不为空时
{
data = Encoding.BigEndianUnicode.GetString(receiveBytes); //接收数据
//接收数据成功后给客户端返回OK
//client.Send(encoding.GetBytes("OK"), 2, 0); receiveBytes = Encoding.BigEndianUnicode.GetBytes(data.ToCharArray());
client.Send(receiveBytes, receiveBytes.Length, 0);
}
else
{
break;
}
}
}
catch (Exception ex)
{
Console.Write("出现异常:");
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
client.Close();
}
}