C# 套接字无法发送数据

发布于 2024-12-07 14:32:57 字数 2561 浏览 1 评论 0原文

大家好,这个方法在客户端计算机上发送文件,

        private void StartServer()
    {
        TcpListener lsn = new TcpListener(IPAddress.Any, 27015);
        Socket sck;

        try
        {
            while (true)
            {
                lsn.Start();
                sck = lsn.AcceptSocket();
                byte[] b = new byte[100];
                int k = sck.Receive(b);
                string recived = "";

                for (int i = 0; i < k; i++)
                {
                    recived = "" + recived + "" + Convert.ToChar(b[i]).ToString();
                }

                if (recived == "Version")
                {
                    string _ipPort = sck.RemoteEndPoint.ToString();

                    var parts = _ipPort.Split(':');
                    _IPAddr = IPAddress.Parse(parts[0]);
                    _Port = Convert.ToInt32(parts[1]);
                    sck.Send(System.Text.Encoding.ASCII.GetBytes("1.1.0.0"));
                }

                k = sck.Receive(b);
                recived = "";

                for (int i = 0; i < k; i++)
                {
                    recived = "" + recived + "" + Convert.ToChar(b[i]).ToString();
                }

                if (recived == "Update")
                {
                    fName = "Cannonball.mp3";

                    byte[] fileName = Encoding.UTF8.GetBytes(fName);
                    byte[] fileData = File.ReadAllBytes("D:\\Cannonball.mp3");
                    byte[] fileNameLen = BitConverter.GetBytes(fileName.Length);

                    clientData = new byte[4 + fileName.Length + fileData.Length];

                    fileNameLen.CopyTo(clientData, 0);
                    fileName.CopyTo(clientData, 4);
                    fileData.CopyTo(clientData, 4 + fileName.Length);

                    if (sck.Connected == true)
                    {
                        sck.Send(clientData);
                        sck.Close();
                    }

                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message.ToString());
        }
    }

当它到达最后一个 if 语句时不执行任何操作。我编写了这段代码

Socket sck1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        sck1.Connect(_IPAddr, _Port);
                        sck1.Send(clientData);

,但 Visual Studio 给出了无法建立连接的错误。 我尝试了 999 端口,我知道该端口已打开 sck1.Connect(_IPAddr, 999); 并且客户端收到了文件。 有谁知道我如何将文件发送到服务器获得的远程端点(sck.RemoteEndPoint)?

Hello guys this method sending file on client machine

        private void StartServer()
    {
        TcpListener lsn = new TcpListener(IPAddress.Any, 27015);
        Socket sck;

        try
        {
            while (true)
            {
                lsn.Start();
                sck = lsn.AcceptSocket();
                byte[] b = new byte[100];
                int k = sck.Receive(b);
                string recived = "";

                for (int i = 0; i < k; i++)
                {
                    recived = "" + recived + "" + Convert.ToChar(b[i]).ToString();
                }

                if (recived == "Version")
                {
                    string _ipPort = sck.RemoteEndPoint.ToString();

                    var parts = _ipPort.Split(':');
                    _IPAddr = IPAddress.Parse(parts[0]);
                    _Port = Convert.ToInt32(parts[1]);
                    sck.Send(System.Text.Encoding.ASCII.GetBytes("1.1.0.0"));
                }

                k = sck.Receive(b);
                recived = "";

                for (int i = 0; i < k; i++)
                {
                    recived = "" + recived + "" + Convert.ToChar(b[i]).ToString();
                }

                if (recived == "Update")
                {
                    fName = "Cannonball.mp3";

                    byte[] fileName = Encoding.UTF8.GetBytes(fName);
                    byte[] fileData = File.ReadAllBytes("D:\\Cannonball.mp3");
                    byte[] fileNameLen = BitConverter.GetBytes(fileName.Length);

                    clientData = new byte[4 + fileName.Length + fileData.Length];

                    fileNameLen.CopyTo(clientData, 0);
                    fileName.CopyTo(clientData, 4);
                    fileData.CopyTo(clientData, 4 + fileName.Length);

                    if (sck.Connected == true)
                    {
                        sck.Send(clientData);
                        sck.Close();
                    }

                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message.ToString());
        }
    }

When its goes to last if statment does not doing nothing. I wrote this code

Socket sck1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        sck1.Connect(_IPAddr, _Port);
                        sck1.Send(clientData);

but visual studio gives error that cannot establish connection.
I tried 999 port which i knew was open sck1.Connect(_IPAddr, 999); and client recieved file.
Does anyone know how i can send file that remote endpoint(sck.RemoteEndPoint) which server got ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你拒绝所有暧昧 2024-12-14 14:32:57

如果 sck1.Connect(_IPAddr, 999) 连接到服务器计算机上的某个套接字,则至少 _IPAddr 的值是正确的。

当您尝试连接时,您是否检查过 _Port 的值?它与服务器正在侦听的端口号匹配吗?

如果这些数字匹配,您可以尝试以下操作来测试您的服务器是否可访问:

  • 启动服务器应用程序
  • 在客户端计算机上,打开浏览器并键入: http://111.11.11.111:27015(将 111 替换为实际 IP 地址)
  • 如果服务器接受该套接字一旦服务器可以访问,您就需要关注客户端应用程序而不是服务器。

If sck1.Connect(_IPAddr, 999) connects to some socket on the server's machine, then at least the value of _IPAddr is correct.

Did you check what value _Port has when you are trying to connect? Does it match the port number the server is listening at?

If these numbers match, you could try the following to test if your server is reachable:

  • Start the server application
  • On the client machine, open a browser and type: http://111.11.11.111:27015 (replace the 111's with the actual IP address)
  • If the server accepts a socket at that time, the server is reachable and you'll need to focus on the client application rather than the server.
巴黎夜雨 2024-12-14 14:32:57

尝试使用 TCPClientTCPListener 而不是套接字。

编辑:因为您在这里遇到不止一个问题。我决定向你们展示我是多么喜欢做这样的事情。

using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

public static class Server
{
    private static Thread _listenThread;

    public static IPEndPoint ServerEp { get; set; }

    private static TcpListener _listener;

    // Listens for clients and creates a new thread to talk to each client on
    private static void ListenMain()
    {
        /* Start Lisening */

        _listener = new TcpListener(ServerEp);
        _listener.Start();

        while (true)
        {
            TcpClient newClient = _listener.AcceptTcpClient();

            // Create a thread to handle client communication
            var clientThread = new Thread((ClientComm)) {IsBackground = true};



            clientThread.Start(newClient);
        }

    }

    // The Client Communcation Method
    private static void ClientComm(object clientobject)
    {
        TcpClient client = (TcpClient) clientobject;
        NetworkStream stream = client.GetStream();

        while (true)
        {
            try
            {
                var message = RecieveMessage(client);

                // process the message object as you see fit.
            }
            catch
            {
                if (!client.Connected)
                {
                    break;
                }
            }

            // you could create a wrapper object for the connections
            // give each user a name or whatever and add the disconnect code here
        }
    }

    private static DataMessage RecieveMessage(TcpClient client)
    {
        NetworkStream stream = client.GetStream();

        IFormatter formatter = new BinaryFormatter();

        return (DataMessage)formatter.Deserialize(stream);
    }

    public static void SendMessage(DataMessage message, TcpClient client)
    {
        IFormatter formatter = new BinaryFormatter();

        formatter.Serialize(client.GetStream(), message);
    }

    // Starts...
    // You could add paramaters to this if you need to I like to set with Server.Etc
    public static void Start()
    {
        try
        {
            if (_listenThread.IsAlive) return;
        }
        catch (NullReferenceException)
        {
            _listenThread = new Thread(ListenMain) { IsBackground = true };
        }

        _listenThread.Start();
    }
}

// Must be in both client and server in a shared .dll
// All properties must be serializable
[Serializable]
public class DataMessage
{
    public string StringProp{ get; set; }

    public int IntProp { get; set; }

    public bool BoolProp { get; set; }

    // will cause an exception on serialization. TcpClient isn't marked as serializable.
  /*   public TcpClient Client { get; set; } */
}

如果您需要的话,我会发布我的客户。 :)
祝你好运!

Try using TCPClient and TCPListener instead of Sockets.

EDIT: Since your having more than one problem here. I decided to show you how I like to do something like this.

using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

public static class Server
{
    private static Thread _listenThread;

    public static IPEndPoint ServerEp { get; set; }

    private static TcpListener _listener;

    // Listens for clients and creates a new thread to talk to each client on
    private static void ListenMain()
    {
        /* Start Lisening */

        _listener = new TcpListener(ServerEp);
        _listener.Start();

        while (true)
        {
            TcpClient newClient = _listener.AcceptTcpClient();

            // Create a thread to handle client communication
            var clientThread = new Thread((ClientComm)) {IsBackground = true};



            clientThread.Start(newClient);
        }

    }

    // The Client Communcation Method
    private static void ClientComm(object clientobject)
    {
        TcpClient client = (TcpClient) clientobject;
        NetworkStream stream = client.GetStream();

        while (true)
        {
            try
            {
                var message = RecieveMessage(client);

                // process the message object as you see fit.
            }
            catch
            {
                if (!client.Connected)
                {
                    break;
                }
            }

            // you could create a wrapper object for the connections
            // give each user a name or whatever and add the disconnect code here
        }
    }

    private static DataMessage RecieveMessage(TcpClient client)
    {
        NetworkStream stream = client.GetStream();

        IFormatter formatter = new BinaryFormatter();

        return (DataMessage)formatter.Deserialize(stream);
    }

    public static void SendMessage(DataMessage message, TcpClient client)
    {
        IFormatter formatter = new BinaryFormatter();

        formatter.Serialize(client.GetStream(), message);
    }

    // Starts...
    // You could add paramaters to this if you need to I like to set with Server.Etc
    public static void Start()
    {
        try
        {
            if (_listenThread.IsAlive) return;
        }
        catch (NullReferenceException)
        {
            _listenThread = new Thread(ListenMain) { IsBackground = true };
        }

        _listenThread.Start();
    }
}

// Must be in both client and server in a shared .dll
// All properties must be serializable
[Serializable]
public class DataMessage
{
    public string StringProp{ get; set; }

    public int IntProp { get; set; }

    public bool BoolProp { get; set; }

    // will cause an exception on serialization. TcpClient isn't marked as serializable.
  /*   public TcpClient Client { get; set; } */
}

I'll post my client if you need me to. :)
Good Luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文