| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2258 人关注过本帖
标题:socket大神麻烦看看,实在找不出问题!!
取消只看楼主 加入收藏
张钊1993
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-7-6
收藏
 问题点数:0 回复次数:0 
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;
                }
            }
        }
    }
}
搜索更多相关主题的帖子: socket private static new Thread 
2018-07-06 22:50
快速回复:socket大神麻烦看看,实在找不出问题!!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.353386 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved