c# - 服务器/客户端套接字连接

标签 c# sockets

我正在尝试通过套接字连接将数据从客户端发送到服务器。我成功发送了第一个数据,但是当我尝试发送第二个数据时它从未发送,当我尝试发送第三个数据时它给我 Sockets.SocketException 我该如何解决?

服务器

byte[] buffer = new byte[1000];


        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = iphostInfo.AddressList[0];
        IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080);

        Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


        sock.Bind(localEndpoint);
        sock.Listen(5);



        while (true) {
            Socket confd = sock.Accept();

            string data = null;

            int b = confd.Receive(buffer);

            data += Encoding.ASCII.GetString(buffer, 0, b);

            Console.WriteLine("" + data);

            confd.Close();
        }

客户端

byte[] data = new byte[10];

        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAdress = iphostInfo.AddressList[0];
        IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080);

        Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


        try {

            client.Connect(ipEndpoint);
            Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());


            while (true) {

                string message = Console.ReadLine();
                byte [] sendmsg = Encoding.ASCII.GetBytes(message);
                int n = client.Send(sendmsg);
            }


        }
        catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("Transmission end.");
        Console.ReadKey();

最佳答案

好吧,多么愚蠢的错误。这是解决方案,我们应该接受一次套接字。

while (true) {
    Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    confd.Close();
}

改为

Socket confd = sock.Accept();
while (true) {
    //Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    //confd.Close();
}

如果有任何关于套接字的文档,请发表评论。我想读书。

关于c# - 服务器/客户端套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951756/

相关文章:

c# - 使用 incell 编辑在网格中解析 Kendo 日期,ASP.NET MVC

c# - 选择美观的随机颜色

php - PHP中的TCP/套接字,撑起我的线程?

c++ - 从 QLocalSocket 读取超过 2048 个字节

Java 套接字 : can I write a TCP server with one thread?

sockets - TCP sockets 和 web sockets 的区别,再来一次

c# - 将codeunits dart转换为Encoding.Unicode C#

c# - 如何向 webform 项目添加回调

c# - XAML Horizo​​ntalAlignment 属性不符合我的要求

c - 带有 SIOCSIFFLAGS 的 setsockopt 和 ioctl 有什么区别?