【问题标题】:C# sockets cannot sent dataC# 套接字无法发送数据
【发布时间】:2011-10-03 23:21:17
【问题描述】:

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

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

如果语句没有做任何事情,它会持续到最后。我写了这段代码

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)的文件?

【问题讨论】:

  • 这是干什么用的? recived = "" + recived + "" +...,我错过了什么还是和recived +=...一样?

标签: c# sockets tcp stream


【解决方案1】:

如果sck1.Connect(_IPAddr, 999) 连接到服务器机器上的一些 套接字,那么至少_IPAddr 的值是正确的。

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

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

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

【讨论】:

  • 附言。 “如果声明什么都不做,那么当它持续下去时”是什么意思。如果您甚至无法连接到服务器?
  • 我的意思是当 if 结束时,它会继续循环。当客户端应用程序发送“更新”tcp 监听器开始监听 _Port 并且我得到 _Port 像 tihs : string lep = sck.LocalEndPoint.ToString(); var 零件 = lep.Split(':'); _Port = Convert.ToInt32(parts[1]);
  • 您发布的代码需要发送两个命令。第一个命令可以是“版本”,否则将被忽略。在“版本”部分之后,您有另一个 Receive,阻塞直到收到第二个命令。如果第二个命令是“更新”,它将发送数据。您的故事的其余部分非常模糊,您似乎遇到了多个问题而不是一个?
【解决方案2】:

尝试使用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; } */
}

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

【讨论】:

  • 在此处发布您的 TCPClient 代码。以及您到底想用它做什么。
猜你喜欢
  • 2014-03-15
  • 2013-09-13
  • 2020-02-29
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2018-09-13
相关资源
最近更新 更多