Click here to Skip to main content
15,893,668 members
Home / Discussions / C#
   

C#

 
AnswerRe: filling a column with property value of object Pin
OriginalGriff14-Apr-20 21:34
mveOriginalGriff14-Apr-20 21:34 
QuestionTarga files displayed in openFileDialog Pin
MikeBr13-Apr-20 22:26
MikeBr13-Apr-20 22:26 
AnswerRe: Targa files displayed in openFileDialog Pin
OriginalGriff13-Apr-20 23:19
mveOriginalGriff13-Apr-20 23:19 
AnswerRe: Targa files displayed in openFileDialog Pin
Richard Deeming14-Apr-20 0:15
mveRichard Deeming14-Apr-20 0:15 
AnswerRe: Targa files displayed in openFileDialog Pin
Dave Kreskowiak14-Apr-20 4:37
mveDave Kreskowiak14-Apr-20 4:37 
QuestionProgramming Tcp with C# Pin
Member 1478193513-Apr-20 21:13
Member 1478193513-Apr-20 21:13 
AnswerRe: Programming Tcp with C# Pin
OriginalGriff13-Apr-20 21:25
mveOriginalGriff13-Apr-20 21:25 
GeneralRe: Programming Tcp with C# Pin
Member 1478193519-Apr-20 3:24
Member 1478193519-Apr-20 3:24 
Dear all,

I have two applications:

Console one it server for Tcp pertinant socket :

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

using System.IO;

namespace Asychn_Server
{
    // State object for reading client data asynchronously  
    public class StateObject
    {
        // Client  socket.  
        public Socket workSocket = null;
        // Size of receive buffer.  
        public const int BufferSize = 1024;
        // Receive buffer.  
        public byte[] buffer = new byte[BufferSize];
        // Received data string.  
        public StringBuilder sb = new StringBuilder();
    }
    public class AsynchronousSocketListener
    {
        // Thread signal.  
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public AsynchronousSocketListener()
        {
        }

        public static void StartListening()
        {
            // Establish the local endpoint for the socket.  
            // The DNS name of the computer  
            // running the listener is "host.contoso.com".  
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.  
            Socket listener = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.  
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.  
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.  
                    Console.WriteLine("Waiting for a connection...");
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

                    // Wait until a connection is made before continuing.  
                    allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();

        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.  
            allDone.Set();

            // Get the socket that handles the client request.  
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.  
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket  
            // from the asynchronous state object.  
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.  
                state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.  
                content = state.sb.ToString();

                log("Socket status : " + handler.Connected);
                log("From socket : " + content);
                // Echo the data back to the client.  
                Send(handler, content);
                log("Socket status : " + handler.Connected);
                //if (content.IndexOf("<EOF>") > -1)
                //{
                //    // All the data has been read from the
                //    // client. Display it on the console.  
                //    //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                //    //    content.Length, content);
                //    log("From socket : " + content);
                //    // Echo the data back to the client.  
                //    Send(handler, content);
                //}
                //else
                //{
                //    // Not all data received. Get more.  
                //    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                //    new AsyncCallback(ReadCallback), state);
                //}
            }
        }

        private static void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.  
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.  
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.  
                int bytesSent = handler.EndSend(ar);
                //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
                  log("TO socket : " + bytesSent + " -As reply");
                log("Socket status send: " + handler.Connected);
                allDone.Set();
                //handler.Shutdown(SocketShutdown.Both);
                //handler.Close();
                log("Socket status send2: " + handler.Connected);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public static int Main(String[] args)
        {
            StartListening();
            return 0;
        }

        public  static void log(string strLog)
        {
            StreamWriter log;
            FileStream fileStream = null;
            DirectoryInfo logDirInfo = null;
            FileInfo logFileInfo;

            string logFilePath = "C:\\Logs\\";
            logFilePath = logFilePath + "LogServer-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
            logFileInfo = new FileInfo(logFilePath);
            logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
            if (!logDirInfo.Exists) logDirInfo.Create();
            if (!logFileInfo.Exists)
            {
                fileStream = logFileInfo.Create();
            }
            else
            {
                fileStream = new FileStream(logFilePath, FileMode.Append);
            }
            log = new StreamWriter(fileStream);
            log.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": " + strLog);
            log.Close();
        }
    }
}


And client one as Desktop Application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//using System.Text;
using System.IO;

namespace Asynch_client_form_2
{
   
    public partial class Form1 : Form
    {
        // The port number for the remote device.  
        private const int port = 11000;

        // ManualResetEvent instances signal completion.  
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);

        // The response from the remote device.  
        private static String response = String.Empty;
        private static Socket client;

        private void ConnectBtn_Click(object sender, EventArgs e)
        {
            try
            {
                // Establish the remote endpoint for the socket.  
                // The name of the
                // remote device is "host.contoso.com".  
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.  
                //Socket client = new Socket(ipAddress.AddressFamily,
                //    SocketType.Stream, ProtocolType.Tcp);

                client = new Socket(ipAddress.AddressFamily,
                   SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.  
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();
/*
                // Send test data to the remote device.  
                Send(client, "This is a test<EOF>");
                sendDone.WaitOne();

                // Receive the response from the remote device.  
                Receive(client);
                receiveDone.WaitOne();
                MsgTextBox.Text = response;*/
            }
            catch (Exception ex)
            {
                ExceptionTextBox.Text = ex.Message;
            }
        }
        private void SendBtn_Click(object sender, EventArgs e)
        {
            try
            { 
            // Send test data to the remote device.  
             //Send(client, MsgTextBox.Text );
                Send(client, "MY message");
                sendDone.WaitOne();

            // Receive the response from the remote device.  
            Receive(client);
            // receiveDone.WaitOne();
            MsgTextBox.Text = response;
            }
            catch (Exception ex)
            {
                ExceptionTextBox.Text = ex.Message;
            }
        }
        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.  
                client.EndConnect(ar);

                /* Console.WriteLine("Socket connected to {0}",
                     client.RemoteEndPoint.ToString());*/

                // Signal that the connection has been made.  
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        private void DisConnectBtn_Click(object sender, EventArgs e)
        {
            // Release the socket.  
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public Form1()
        {
            InitializeComponent();
        }
        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.  
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.  
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
              log(e.ToString());
            }
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.  
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;

                // Read data from the remote device.  
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.  
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Get the rest of the data.  
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    // All the data has arrived; put it in response.  
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                        log("Reply : " + response);
                    }
                    // Signal that all bytes have been received.  
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
               log(e.ToString());
            }
        }

        private static void Send(Socket client, String data)
        {
            // Convert the string data to byte data using ASCII encoding.  
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.  
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.  
                int bytesSent = client.EndSend(ar);
               // Console.WriteLine("Sent {0} bytes to server.", bytesSent);

                // Signal that all bytes have been sent.  
                sendDone.Set();
            }
            catch (Exception e)
            {
               log (e.ToString());
            }
        }
        public static void log(string strLog)
        {
            StreamWriter log;
            FileStream fileStream = null;
            DirectoryInfo logDirInfo = null;
            FileInfo logFileInfo;

            string logFilePath = "C:\\Logs\\";
            logFilePath = logFilePath + "LogClient-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
            logFileInfo = new FileInfo(logFilePath);
            logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
            if (!logDirInfo.Exists) logDirInfo.Create();
            if (!logFileInfo.Exists)
            {
                fileStream = logFileInfo.Create();
            }
            else
            {
                fileStream = new FileStream(logFilePath, FileMode.Append);
            }
            log = new StreamWriter(fileStream);
            log.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": " + strLog);
            log.Close();
        }
    }
}

In Client i need to press connect in order to estabish socket
and after that press send bouton to send messages without disconnecting socket.
with this code i couldn't handle reply for my message from server.
Can someone help me please
QuestionSaving usercontrol design-time properties Pin
Crazy Joe Devola13-Apr-20 14:49
Crazy Joe Devola13-Apr-20 14:49 
AnswerRe: Saving usercontrol design-time properties Pin
OriginalGriff13-Apr-20 20:00
mveOriginalGriff13-Apr-20 20:00 
AnswerRe: Saving usercontrol design-time properties Pin
Richard Deeming14-Apr-20 0:13
mveRichard Deeming14-Apr-20 0:13 
GeneralRe: Saving usercontrol design-time properties Pin
Crazy Joe Devola14-Apr-20 13:45
Crazy Joe Devola14-Apr-20 13:45 
QuestionPrint Multiple Page in c# Pin
Mohamed Fahad13-Apr-20 9:08
Mohamed Fahad13-Apr-20 9:08 
AnswerRe: Print Multiple Page in c# Pin
Pete O'Hanlon13-Apr-20 9:30
mvePete O'Hanlon13-Apr-20 9:30 
QuestionMulti threading in c# Pin
User-862169513-Apr-20 1:49
User-862169513-Apr-20 1:49 
AnswerRe: Multi threading in c# Pin
OriginalGriff13-Apr-20 3:00
mveOriginalGriff13-Apr-20 3:00 
QuestionOPC Client Using C# Titanium Library Pin
Member 147907399-Apr-20 20:17
Member 147907399-Apr-20 20:17 
AnswerRe: OPC Client Using C# Titanium Library Pin
Gerry Schmitz10-Apr-20 6:46
mveGerry Schmitz10-Apr-20 6:46 
GeneralRe: OPC Client Using C# Titanium Library Pin
Member 1479073910-Apr-20 7:03
Member 1479073910-Apr-20 7:03 
GeneralRe: OPC Client Using C# Titanium Library Pin
Mycroft Holmes10-Apr-20 12:35
professionalMycroft Holmes10-Apr-20 12:35 
AnswerRe: OPC Client Using C# Titanium Library Pin
Pete O'Hanlon14-Apr-20 5:42
mvePete O'Hanlon14-Apr-20 5:42 
Questiontextbox update Pin
_Q12_9-Apr-20 19:19
_Q12_9-Apr-20 19:19 
AnswerRe: textbox update Pin
_Q12_9-Apr-20 21:20
_Q12_9-Apr-20 21:20 
AnswerRe: textbox update Pin
Gerry Schmitz10-Apr-20 6:43
mveGerry Schmitz10-Apr-20 6:43 
AnswerRe: textbox update Pin
BillWoodruff16-Apr-20 18:06
professionalBillWoodruff16-Apr-20 18:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.