socket大神麻烦看看,实在找不出问题!!
namespace SocketServer{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 9000; //端口
static Socket serverSocket;
static List<Socket> socketlist = new List<Socket>();
static void Main(string[] args)
{
//绑定IP地址:端口
IPAddress ip = IPAddress.Any;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt));
serverSocket.Listen(10);
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
socketlist.Add(clientSocket);
clientSocket.Send(Encoding.Default.GetBytes("你已经连接上服务器"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// 接收消息
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
temp=Encoding.Default.GetString(result, 0, receiveNumber);
//给客户端群发消息,为什么不对,应该怎么修改????求求大神帮忙看看,不胜感激
foreach (Socket sl in socketlist)
{
sl.Send(Encoding.Default.GetBytes(temp));
}
Console.WriteLine("接收消息为:{0}", temp);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}