Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Dear reader,

I am wondering if i am going about this socket programming all wrong. My code is functional but i just have my doubts this is correct. I will be posting code in execution order.

Server:

Listen for connections
C#
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 1500);
mainSocket.Bind(ipLocal);
mainSocket.Listen(-1);

mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);


//Request a file
//Set first to transfer command, 1-8 uri length, ASCII data
C#
private void TransferFile(string uri)
{
    byte[] tmp = ASCIIEncoding.ASCII.GetBytes(uri);
    byte[] data = new byte[tmp.Length + 9];
    BitConverter.GetBytes((long)tmp.Length).CopyTo(data, 1);
    tmp.CopyTo(data, 9);
    data[0] = (byte)cmd.transfer;
    SendPacket(clientSocket, data);
}
public void SendPacket(SocketPacket to, byte[] p)
{
    if (!IsConnected(to.currentSocket))
    {
        Disconnect(to);
        return;
    }
    try
    {
        NetworkStream networkStream = new NetworkStream(to.currentSocket);
        networkStream.Write(p, 0, p.Length);
    }
    catch (Exception)
    {
    }
}


Client:

//connect to server and wait for commands
C#
public void start()
{
try
{
    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
    IPEndPoint ipEnd = new IPEndPoint(IPAddress.Loopback, 1500);
    clientSocket.Connect(ipEnd);
    WaitForData();
}
catch (Exception)
{
}
}

public void WaitForData()
{
try
{
    if (pfnCallBack == null)
    {
        pfnCallBack = new AsyncCallback(OnDataReceived);
    }
    SocketPacket theSocPkt = new SocketPacket(clientSocket);
    result = clientSocket.BeginReceive(theSocPkt.Buffer, 0, 9, SocketFlags.None, pfnCallBack, theSocPkt);
}
catch (Exception)
{}
}


//File transfer request received
C#
public void OnDataReceived(IAsyncResult asyn)
{
try
{
    byte[] tmp = new byte[1024];
    string msg = string.Empty;
    long length = 0;
    long rdby = 0;
    int len = 0;
    SocketPacket s = (SocketPacket)asyn.AsyncState;
    NetworkStream nfs = new NetworkStream(s.currentSocket);

    //Read byte 1-8 from BeginReceive buffer to length
    length = BitConverter.ToInt64(s.Buffer, 1);
    //Read byte 0 with command
    switch (s.Buffer[0])
    {
        case (int)cmd.transfer:
        while (rdby < length)
        {
            len = nfs.Read(tmp, 0, pSize);
            if (len == 0) if (!IsConnected(s.currentSocket)) { Dispose(); Start(); };
            msg += ASCIIEncoding.ASCII.GetString(tmp, 0, len);
            rdby = rdby + len;
        }
        SendFile(s.currentSocket, msg);
        break;
   }
}
catch (Exception)
{}
WaitForData();
}

public void SendFile(Socket s, string file)
{
try
{
    if (clientSocket != null)
    {
        FileInfo fi = new FileInfo(file);

        int len = 0;
        int rdby = 0;

        FileStream fin = new FileStream(file, FileMode.Open, FileAccess.Read);
        NetworkStream nfs = new NetworkStream(s);

        //Send Header, 0= cmd, 1-8 file length
        byte[] tmp = new byte[9];
        BitConverter.GetBytes(fi.Length).CopyTo(tmp, 1);
        tmp[0] = (byte)cmd.transfer;
        nfs.Write(tmp, 0, tmp.Length);

        //Send File
        tmp = new byte[pSize];
        while (rdby < fi.Length && nfs.CanWrite)
        {
            len = fin.Read(tmp, 0, tmp.Length);
            nfs.Write(tmp, 0, len);
            rdby = rdby + len;
        }
        fin.Close();
    }
}
catch { }
}

private bool IsConnected(Socket socket)
{
    try
    {
        if (socket.Connected)
            return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
        else
            return false;
    }
    catch (SocketException) { return false; }
}



Thanks for baring with me,
And hopefully i can learn something from your response.
Posted
Comments
TRK3 13-Jun-11 21:07pm    
Other than the fact that your catch() blocks are empty It seems fine to me.

If it works, what makes you think you are doing it wrong?
Sergey Alexandrovich Kryukov 13-Jun-11 21:48pm    
My personal opinion: you make to to complex by using async sockets. Synchronous sockets with their blocking call and explicit threads are much easier. I think async threads is left-overs from the epoch prior to threads.
--SA

1 solution

I had removed all the exception code to shorten my post.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900