【问题标题】:Client send message server not received message in tcp/ip socket program客户端发送消息服务器未在 tcp/ip 套接字程序中收到消息
【发布时间】:2014-12-19 13:18:24
【问题描述】:

TCP/IP 套接字程序客户端发送文本服务器接收和存储数据库表。我正在纠正下面的代码,但我有错误文本重新审核时间。

这是客户端代码

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


    namespace ClientApplication
    {
        class Client
        {
            static void Main(string[] args)
            {
                try
                {
                    TcpClient tcpclnt = new TcpClient();
                    Console.WriteLine("Connecting.....");

                    //tcpclnt.Connect("162.144.85.232", 8080);
                    tcpclnt.Connect("162.144.85.232", 4489);


                    Console.WriteLine("Connected");
                    Console.Write("Enter the string to be Sent : ");

                    String str = Console.ReadLine();
                    Stream stm = tcpclnt.GetStream();

                    ASCIIEncoding asen = new ASCIIEncoding();
                    byte[] ba = asen.GetBytes(str);
                    System.Net.ServicePointManager.Expect100Continue = false;
                   Console.WriteLine("Sending.....");

                    stm.Write(ba, 0, ba.Length);

                    byte[] bb = new byte[100];
                    int k = stm.Read(bb, 0, 100);

                    for (int i = 0; i < k; i++)
                        Console.Write(Convert.ToChar(bb[i]));

                    Console.ReadLine();

                    tcpclnt.Close();
                    Console.ReadLine();
                }

                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                    Console.ReadLine();
                }
            }
    }
    }

这是服务器端代码

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

namespace ServerApplication
{
    class Server
    {
        static void Main(string[] args)
        {
            try
            {
                IPAddress ipadd = IPAddress.Parse("192.168.1.7");
                TcpListener list = new TcpListener(ipadd, 8080);
                list.Start();
                Console.WriteLine("The server is running at port 8080...");
                Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
                System.Net.ServicePointManager.Expect100Continue = false;
                Socket s = list.AcceptSocket();
                Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
                byte[] b = new byte[100];
                int k = s.Receive(b);
                Console.WriteLine("Recived...");
                for (int i = 0; i < k; i++)
                Console.WriteLine(Convert.ToChar(b[i]));
                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes("The String Was Recived throw Server"));
                Console.WriteLine("\n Sent Acknowlegment");
                s.Close();
                list.Stop();


            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);

            }

        }
}
}

我正在尝试执行此代码,但发生了这样的错误 无法从传输连接读取数据:现有连接被远程主机强行关闭。请解决我的问题。

【问题讨论】:

  • 什么是异常消息
  • Hii CodeCaster 这是我的错误消息。System.dll 中发生了“System.IO.IOException”类型的未处理异常 谢谢
  • 您需要提供更多信息。异常包含此信息。请尝试调试问题。什么是内部异常?此外,当您收到 IOException 时,您的代码会捕获 SocketException,这在 SocketException 的继承链中不存在。
  • 无法从传输连接读取数据:从客户端向服务器发送文本时,远程主机强制关闭了现有连接
  • 您的while (true) 没有意义,试图将多个NetworkStreams 包装在同一个套接字周围。也许这不是 this 问题的原因,那么它将是下一个问题的原因。

标签: c# sockets client-server tcp-ip


【解决方案1】:

您发布的代码存在许多问题,但直接导致您看到的行为是服务器关闭套接字而不等待客户端完成从连接中读取。

查看“TCP 正常关闭”以获取更多信息。同时,以下是对您发布的代码的改进,不会有这个问题:

服务器代码:

class Server
{
    static void Main(string[] args)
    {
        try
        {
            TcpListener list = new TcpListener(IPAddress.Any, 8080);
            list.Start();
            Console.WriteLine("The server is running at port 8080...");
            Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
            Socket s = list.AcceptSocket();
            Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
            byte[] b = new byte[100];
            int k;
            while ((k = s.Receive(b)) > 0)
            {
                Console.WriteLine("Recived...");
                Console.WriteLine(Encoding.ASCII.GetString(b, 0, k));
                s.Send(Encoding.ASCII.GetBytes("The String Was Recived throw Server"));
                Console.WriteLine("\n Sent Acknowlegment");
            }
            s.Shutdown(SocketShutdown.Both);
            s.Close();
            list.Stop();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }
}

客户端代码:

class Client
{
    static void Main(string[] args)
    {
        try
        {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");

            tcpclnt.Connect("192.168.1.7", 8080);

            Console.WriteLine("Connected");
            Console.Write("Enter the string to be Sent : ");

            String str = Console.ReadLine();
            Stream stm = tcpclnt.GetStream();

            byte[] ba = Encoding.ASCII.GetBytes(str);
            Console.WriteLine("Sending.....");

            stm.Write(ba, 0, ba.Length);
            tcpclnt.Client.Shutdown(SocketShutdown.Send);

            byte[] bb = new byte[100];
            int k;

            while ((k = stm.Read(bb, 0, 100)) > 0)
            {
                Console.WriteLine(Encoding.ASCII.GetString(bb, 0, k));
            }

            Console.ReadLine();

            tcpclnt.Close();
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
            Console.ReadLine();
        }
    }
}

这里的关键是服务器和客户端都继续从连接中读取,直到远程端通过调用Socket.Shutdown() 发出没有更多数据要读取的信号。

我还删除了System.Net.ServicePointManager.Expect100Continue 属性的使用,该属性在此代码中没有任何影响。这只会影响使用ServicePoint 类的程序,在这里没有用处。

我也不清楚为什么客户端使用NetworkStream 而不是仅仅获取Client 套接字并直接使用它。 NetworkStream 对象在包装 I/O 时很有用,例如StreamReaderStreamWriter,但在这里您只使用 Stream.Read()Stream.Write(),它们的语义分别与 Socket.Receive()Socket.Send() 完全相同。在任何情况下,请注意,当您使用NetworkStream 对象进行发送和接收时,您仍然需要直接访问底层Socket 实例以正确启动正常关闭(未启动的端点可能只是关闭@987654337 @,因为它在发送和接收完成之前不必关闭)。

我还稍微清理了 ASCII 编码文本的处理。

【讨论】:

  • 嗨,Peter 感谢您提供重播,但我在发送文本一段时间后出现异常错误。无法从传输连接中读取数据:连接尝试失败,因为连接方在一段时间后没有正确响应,或者连接失败,因为连接的主机没有响应。我有上面的例外,比如你能有什么想法吗?谢谢
  • 对不起。这不仅是一个完全不同的问题,而且与Socket API 的错误使用相比,这更有可能是一个底层网络传输问题。请注意两条重要信息:1) 新错误发生在 您成功地运行代码之后,以及 2) 它是失败的连接。通常,如果服务器根本没有运行,或者防火墙阻止访问,或者 NAT 路由器没有转发端口的流量,或者......嗯,有很多原因,就会发生这种情况。我确实希望以上内容至少可以解决您的直接问题。
  • 谢谢彼得现在从客户端到服务器成功接收数据,但是在我如何插入数据库表客户端在控制台应用程序中发送文本之后,你有什么想法请给我发短信。谢谢
  • 嗨...我很高兴您能够让程序正常工作。就将接收到的数据保存到数据库而言,我并不是真正的数据库专家。如果您将该问题作为一个实际的 SO 问题提出,您将获得更好的建议,特别是如果您小心地以特定的、可回答的方式来表达它。这样,更多的人将可以访问它,并且问题不必局限于评论空间。 :)
  • 好的。如何设置从不同客户端接收消息到单个服务器。像上面的程序我如何设置多个客户端。
猜你喜欢
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2013-04-29
  • 2016-05-25
相关资源
最近更新 更多