想做一个可以广播的服务器
可是broadcast()有问题
求大虾指点一二~~不胜感激
源码如下:
using System;
using System.IO;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
private TcpListener tcp;
private Socket s;
public ArrayList connections=new ArrayList(1000);
private serveOne one, you;
public Program()
{
try
{
tcp = new TcpListener(8088);
tcp.Start();
Console.WriteLine("服务器启动~~~~");
while(true)
{
s = tcp.AcceptSocket();
one=new serveOne(s);
connections.Add(one);
}
}
catch(Exception e){}
}
public void broadcast()
{
for (int i = 0; i < connections.Count; i++)
{
you = (serveOne)connections[i];
you.write();
}
}
static void Main(string[] args)
{
Program my = new Program();
Thread th2 = new Thread(new ThreadStart(my.broadcast));
th2.Start();
}
}
class serveOne
{
private Socket socket;
private NetworkStream netWorkStream;
private String str="you connect...",str1 = "", str2;
private StreamReader sr;
private StreamWriter sw;
public serveOne(Socket s)
{
try
{
socket = s;
netWorkStream = new NetworkStream(socket);
sr = new StreamReader(netWorkStream);
sw = new StreamWriter(netWorkStream);
sw.WriteLine(str);
sw.Flush();
Thread th1 = new Thread(new ThreadStart(this.listen));
th1.Start();
}
catch(Exception e){}
}
public void listen()
{
try
{
while (true)
{
str1 = sr.ReadLine();
Console.WriteLine(str1);
}
}
catch (Exception e) { }
}
public void write()
{
try
{
while (true)
{
str2 = Console.ReadLine();
sw.WriteLine(str2);
sw.Flush();
}
}
catch (Exception e) { }
}
}
}