Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a simple Windows form application in which i have a client which works properly. the problem is with the server What i exactly want is there will be a simple textbox in which i will type ipaddress and a button which if i click should send a message on the ip that i typed in textbox.. I have client. Please help me with the server. Thanx in adv!!

[EDIT author="OP"]
but can u help me with this code i want to asynchronously receive data how can i modify this code?

C#
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8000);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
DialogResult m = MessageBox.Show("You Have received a Message!");
if (m == DialogResult.OK)
{
    this.Show();
    this.WindowState = FormWindowState.Normal;
}
label1.Text = "Message: " + stringData;
sock.Close();

[/EDIT]
Posted
Updated 5-Dec-11 1:52am
v2

There are lots of samples of socket programming both here in the Articles and on the wider net which Google will find for you.
 
Share this answer
 
Comments
Prajakta Bhagwat 5-Dec-11 5:50am    
yes i have many examples in my hand but the main thing is that i want to send msg over an ip which i give not on live. I mean i need not want live ip's. i'll type an address and send msg to it.
Richard MacCutchan 5-Dec-11 5:55am    
Fine, but you still need a program at the other end to receive the message and process it.
Prajakta Bhagwat 5-Dec-11 6:04am    
yes that i have works fine but i really dont know to send msg from server only to ip not live ip
Michel [mjbohn] 5-Dec-11 6:39am    
What do you mean with 'not live ip'?
Prajakta Bhagwat 5-Dec-11 6:49am    
look i did try now i am connecting via udp it is working well but in udp everytime i receive data i need to restart the socket? do u have ny such example which receives continuous data?
you can try this client and server code:

Network File sender.cs

public partial class Form1 : Form
    {
        // The TCP client will connect to the server using an IP and a port
        TcpClient tcpClient;
        // The file stream will read bytes from the local file you are sending
        FileStream fstFile;
        // The network stream will send bytes to the server application
        NetworkStream strRemote;

        public Form1()
        {
            InitializeComponent();
        }

        private void ConnectToServer(string ServerIP, int ServerPort)
        {
            // Create a new instance of a TCP client
            tcpClient = new TcpClient();
            try
            {
                // Connect the TCP client to the specified IP and port
                tcpClient.Connect(ServerIP, ServerPort);
                txtLog.Text += "Successfully connected to server\r\n";
            }
            catch (Exception exMessage)
            {
                // Display any possible error
                txtLog.Text += exMessage.Message;
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // Call the ConnectToServer method and pass the parameters entered by the user
            ConnectToServer(txtServer.Text, Convert.ToInt32(txtPort.Text));
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            // If tclClient is not connected, try a connection
            if (tcpClient.Connected == false)
            {
                // Call the ConnectToServer method and pass the parameters entered by the user
                ConnectToServer(txtServer.Text, Convert.ToInt32(txtPort.Text));
            }

            // Prompt the user for opening a file
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                txtLog.Text += "Sending file information\r\n";
                // Get a stream connected to the server
                strRemote = tcpClient.GetStream();
                byte[] byteSend = new byte[tcpClient.ReceiveBufferSize];
                // The file stream will read bytes from the file that the user has chosen
                fstFile = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);
                // Read the file as binary
                BinaryReader binFile = new BinaryReader(fstFile);

                // Get information about the opened file
                FileInfo fInfo = new FileInfo(openFile.FileName);

                // Get and store the file name
                string FileName = fInfo.Name;
                // Store the file name as a sequence of bytes
                byte[] ByteFileName = new byte[2048];
                ByteFileName = System.Text.Encoding.ASCII.GetBytes(FileName.ToCharArray());
                // Write the sequence of bytes (the file name) to the network stream
                strRemote.Write(ByteFileName, 0, ByteFileName.Length);

                // Get and store the file size
                long FileSize = fInfo.Length;
                // Store the file size as a sequence of bytes
                byte[] ByteFileSize = new byte[2048];
                ByteFileSize = System.Text.Encoding.ASCII.GetBytes(FileSize.ToString().ToCharArray());
                // Write the sequence of bytes (the file size) to the network stream
                strRemote.Write(ByteFileSize, 0, ByteFileSize.Length);

                txtLog.Text += "Sending the file " + FileName + " (" + FileSize + " bytes)\r\n";

                // Reset the number of read bytes
                int bytesSize = 0;
                // Define the buffer size
                byte[] downBuffer = new byte[2048];

                // Loop through the file stream of the local file
                while ((bytesSize = fstFile.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    // Write the data that composes the file to the network stream
                    strRemote.Write(downBuffer, 0, bytesSize);
                }

                // Update the log textbox and close the connections and streams
                txtLog.Text += "File sent. Closing streams and connections.\r\n";
                tcpClient.Close();
                strRemote.Close();
                fstFile.Close();
                txtLog.Text += "Streams and connections are now closed.\r\n";
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            // Close connections and streams and update the log textbox
            tcpClient.Close();
            strRemote.Close();
            fstFile.Close();
            txtLog.Text += "Disconnected from server.\r\n";
        }
    }



Network File Receiver.cs

public partial class Form1 : Form
    {
        // The thread in which the file will be received
        private Thread thrDownload;
        // The stream for writing the file to the hard-drive
        private Stream strLocal;
        // The network stream that receives the file
        private NetworkStream strRemote;
        // The TCP listener that will listen for connections
        private TcpListener tlsServer;
        // Delegate for updating the logging textbox
        private delegate void UpdateStatusCallback(string StatusMessage);
        // Delegate for updating the progressbar
        private delegate void UpdateProgressCallback(Int64 BytesRead, Int64 TotalBytes);
        // For storing the progress in percentages
        private static int PercentProgress;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            thrDownload = new Thread(StartReceiving);
            thrDownload.Start();
        }

        private void StartReceiving()
        {
            // There are many lines in here that can cause an exception
            try
            {
                // Get the hostname of the current computer (the server)
                string hstServer = Dns.GetHostName();
                // Get the IP of the first network device, however this can prove unreliable on certain configurations
                IPAddress ipaLocal = Dns.GetHostEntry(hstServer).AddressList[0];
                // If the TCP listener object was not created before, create it
                if (tlsServer == null)
                {
                    // Create the TCP listener object using the IP of the server and the specified port
                    tlsServer = new TcpListener(ipaLocal, Convert.ToInt32(txtPort.Text));
                }
                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Starting the server...\r\n" });
                // Start the TCP listener and listen for connections
                tlsServer.Start();
                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has started. Please connect the client to " + ipaLocal.ToString() + "\r\n" });
                // Accept a pending connection
                TcpClient tclServer = tlsServer.AcceptTcpClient();
                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has accepted the client\r\n" });
                // Receive the stream and store it in a NetworkStream object
                strRemote = tclServer.GetStream();
                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has received the stream\r\n" });

                // For holding the number of bytes we are reading at one time from the stream
                int bytesSize = 0;
                
                // The buffer that holds the data received from the client
                byte[] downBuffer = new byte[2048];
                // Read the first buffer (2048 bytes) from the stream - which represents the file name
                bytesSize = strRemote.Read(downBuffer, 0, 2048);
                // Convert the stream to string and store the file name
                string FileName = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);
                // Set the file stream to the path C:\ plus the name of the file that was on the sender's computer
                strLocal = new FileStream(@"C:\raj\" + FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                // The buffer that holds the data received from the client
                downBuffer = new byte[2048];
                // Read the next buffer (2048 bytes) from the stream - which represents the file size
                bytesSize = strRemote.Read(downBuffer, 0, 2048);
                // Convert the file size from bytes to string and then to long (Int64)
                long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize));

                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Receiving file " + FileName + " (" + FileSize + " bytes)\r\n" });

                // The buffer size for receiving the file
                downBuffer = new byte[2048];

                // From now on we read everything that's in the stream's buffer because the file content has started
                while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    // Write the data to the local file stream
                    strLocal.Write(downBuffer, 0, bytesSize);
                    // Update the progressbar by passing the file size and how much we downloaded so far to UpdateProgress()
                    this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { strLocal.Length, FileSize });
                }
                // When this point is reached, the file has been received and stored successfuly
            }
            finally
            {
                // This part of the method will fire no matter wether an error occured in the above code or not

                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The file was received. Closing streams.\r\n" });

                // Close the streams
                strLocal.Close();
                strRemote.Close();

                // Write the status to the log textbox on the form (txtLog)
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Streams are now closed.\r\n" });

                // Start the server (TCP listener) all over again
                StartReceiving();
            }
        }

        private void UpdateStatus(string StatusMessage)
        {
            // Append the status to the log textbox text 
            txtLog.Text += StatusMessage;
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            if (TotalBytes > 0)
            {
                // Calculate the download progress in percentages
                PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
                // Make progress on the progress bar
                prgDownload.Value = PercentProgress;
            }
        }


        private void btnStop_Click(object sender, EventArgs e)
        {
            strLocal.Close();
            strRemote.Close();
            txtLog.Text += "Streams are now closed.\r\n";
        }

        private void btnStop_Click_1(object sender, EventArgs e)
        {
           
        }
    }
 
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