客户端发送消息服务器未收到 tcp/ip 套接字程序中的消息

本文关键字:消息 ip 套接字 程序 tcp 服务器 客户端 | 更新日期: 2023-09-27 18:34:40

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);
            }
        }
}
}

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

客户端发送消息服务器未收到 tcp/ip 套接字程序中的消息

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

查找"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实例以正确启动优雅关闭(未启动的端点可能只是关闭NetworkStream,因为它不必关闭,直到它完成发送和接收(。

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