监听后,请调用accept方法,
这个访问是一个阻塞式的方法,会一直等待,直到有客户端连接才会执行下去,
这个方法的返回是一个socket
具体的用法,请查看帮助。

解决方案 »

  1.   

    这种占资源吗?是不是可以象线程那样做成一个
    while(true)
    {
    s.accept()
    }
    然后程序如果要做其他事情呢?
    例如:我要做一个聊天软件,只要能发送能接收就行了。
    如果A发到B,B的屏幕能立即显示A发过来的内容,但B也能同时发给A,我该怎么做?
      

  2.   

    服务端:
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;public class datatimeserver{ public static void Main(){ DateTime now;
    String strDateLine;
    Encoding ASCII = Encoding.ASCII;
        try{
    TcpListener tcpl = new TcpListener(6789);
    tcpl.Start();
    Console.WriteLine("Server start");
    Console.WriteLine("Waiting for clients to connect"); while (true) {
    Socket s = tcpl.AcceptSocket();
    now = DateTime.Now;
    strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
    Byte[] byteDateLine = ASCII.GetBytes(strDateLine.ToCharArray());
    s.Send(byteDateLine, byteDateLine.Length, 0);
    Console.WriteLine(s.LocalEndPoint);
    Console.WriteLine(s.RemoteEndPoint);
    s.Close();
    Console.WriteLine("Sent {0}", strDateLine);
    }
        }
        catch (SocketException socketError){
    Console.WriteLine(socketError);
    }
    }
    }
      

  3.   

    客户端:
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Text;public class datatimeclient { public static void Main(String[] args) { TcpClient tcpc = new TcpClient();
    Byte[] read = new Byte[32]; if (args.Length != 1){
    Console.WriteLine("Please input a server name in the command line");
    return;
    }
    String server = args[0]; if (Dns.GetHostByName(server) == null) {
    Console.WriteLine("Cannot find server: {0}", server);
    return;
    }
    tcpc.Connect(server, 6789);
    Stream s;
    try {
    s = tcpc.GetStream();
    } catch (InvalidOperationException) {
    Console.WriteLine("Cannot connect to server: {0}", server);
    return;
    } int bytes = s.Read(read, 0, read.Length);
    String Time = Encoding.ASCII.GetString(read); Console.WriteLine("Received {0} bytes", bytes);
    Console.WriteLine("Current date and time is: {0}", Time); tcpc.Close(); Console.WriteLine("Press Return to exit");
    Console.ReadLine();
    }
    }
      

  4.   

    我自己找到了更好的答案,用异步调用,就是那个beginretrieve的,就能实现