Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am developing a communications program to send all data from multiple serial ports of a computer using TCPIP. To do this we will use PortSerial classes, BackgroundWorket and Socket.

I have already made the reception of data by multiple serial ports. I used to do a FIFO queue in which they mentiendo all data received by the different serial ports are then extracted.

The idea is to send each statement received through TCPIP to another computer. So I have to implement a server and a client part. The server side is implemented in the same program that capture all the data.

The socket server will send all data to customers, and customers will send a name to know who is connecting.

The first poblema I've found is that when trying to run the server in a thread I stuck the whole program.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace RIT_Communicator
{
    public class RIT_SocketServer
    {
        private const int sampleTcpPort = 13000;
        public Thread sampleTcpThread;

        public RIT_SocketServer()
        {
            try
            {
                //Starting the TCP Listener thread.
                sampleTcpThread = new Thread(new ThreadStart(StartListen2));
                sampleTcpThread.Start();
                Console.WriteLine("Started SampleTcpUdpServer's TCP Listener Thread!\n");
            }
            catch (Exception e)
            {
                Console.WriteLine("An TCP Exception has occurred!" + e.ToString());
                sampleTcpThread.Abort();
            }        
        }

        private void StartListen2()
        {
            //Create an instance of TcpListener to listen for TCP connection.
            TcpListener tcpListener = new TcpListener(sampleTcpPort);
            try
            {
                while (true)
                {
                    tcpListener.Start();
                    //Program blocks on Accept() until a client connects.
                    Socket soTcp = tcpListener.AcceptSocket();
                    Console.WriteLine("SampleClient is connected through TCP.");
                    Byte[] received = new Byte[512];
                    int bytesReceived = soTcp.Receive(received, received.Length, 0);
                    String dataReceived = System.Text.Encoding.ASCII.GetString(received);
                    Console.WriteLine(dataReceived);
                    String returningString = "The Server got your message through TCP: " +
                    dataReceived;
                    Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes
                    (returningString.ToCharArray());
                    //Returning a confirmation string back to the client.
                    soTcp.Send(returningByte, returningByte.Length, 0);
                    tcpListener.Stop();
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine("A Socket Exception has occurred!" + se.ToString());
            }
        }

    }
}


It is the first time working with Sockets, and watching several examples online, this is the closest thing I've found to what I would need.

The idea is to launch a server socket thread, since in other threads are doing catching the serial data and also have to display a set of data on the main screen.
Posted
Comments
Mike Meinz 15-Mar-13 17:13pm    
I think the issue is that you need to use the option to do TCP/IP communication Asynchronously rather than Synchronously. Using the Asynchronous options, the program does not have to wait for TCP/IP communication. Instead, events are triggered when TCP/IP completes an operation or otherwise wants attention.

 
Share this answer
 
Hi thanks for the reply, I have adapted the code for asynchronous programming.

I created a list of backgrounworkers each associated with a serial port. I created a function to open all and close all but one in particular I want to open or close one in particular as not locate within the processes that are running. Can you make a process with a value, or a value to pass BackgroundWorker and go all ask for?

C#
        private List<backgroundworker> _workers = new List<backgroundworker>();

        ......

        public void OpenAll()
        {

            string[] portNames = SerialPort.GetPortNames();

            foreach (string name in portNames)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.WorkerSupportsCancellation = true;
                bw.WorkerReportsProgress = true;
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                // Add the worker to the list of workers
                _workers.Add(bw);
                bw.RunWorkerAsync(name);
            }           
        }

</backgroundworker></backgroundworker>


Another problem I have is that by canceling all processes stuck me here (while (bw.IsBusy){}:

C#
public void CancelAllWorkers()
{
    foreach (BackgroundWorker bw in _workers)
    {
        // If the worker is busy - cancel it
        if (bw.IsBusy)
        {
            bw.CancelAsync();

            while (bw.IsBusy) {  }

            bw.DoWork -= new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.Dispose();

            _workers.Remove(bw);
        }
    }
}
 
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