日期:2014-05-17  浏览次数:20854 次

新手SOCKET求救
當我客戶端一關...伺服就會出現問題

C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace serverCs
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("192.168.1.101");
            IPEndPoint ipe = new IPEndPoint(ip, 69999);

            Socket server_socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server_socket.Bind(ipe);
            server_socket.Listen(10);
            listenclient lc = new listenclient(server_socket);
            ThreadStart sts = new ThreadStart(lc.stp);
            Thread st = new Thread(sts);
            st.Start();

        }
    }
    class listenclient
    {
        Socket sevsocket;
        Socket client_socket;
        byte[] say = new byte[1024];
        Int32 received;
        public listenclient(Socket server_socket)
        {
            sevsocket = server_socket;
        }

        public void stp()
        {
            while (true)
            {
                client_socket = sevsocket.Accept();

                IPEndPoint cinfo = (IPEndPoint)client_socket.RemoteEndPoint;

                Console.WriteLine(cinfo.Address.ToString() + ":" + cinfo.Port.ToString() + "進入");


                client_socket.BeginReceive(say, 0, say.Length, SocketFlags.None, new AsyncCallback(rcallback), client_socket);

            }
        }
        public void rcallback(IAsyncResult asy)
        {
            Socket clientsocket = (Socket)asy.AsyncState;

                received = clientsocket.EndReceive(asy);
                  if (received > 0)
                   {
                        Console.WriteLine("{0}", Encoding.UTF8.GetString(say, 0, received));
                        clientsocket.BeginReceive(say, 0, say.Length, SocketFlags.None, new AsyncCallback(rcallback), client_socket);
                  }
                 
        }
    }
}




------解决方案--------------------
Socket server_socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
这一句中的第一个参数应该是ip.AddressFamily.InterNetwork