开发者

C# sockets cannot sent data

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++)
               开发者_如何学C {
                    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 ?


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜