473,396 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

2 way socket between applications/devices

I am new to C# and am writing a program that will run on a pc and allow either another program or an external device, like a touchpanel control system, to connect to it. I have the rest of my code ready, but I can't figure out how to make the socket connection work.
I need the following

My application listens for a connection.
Device connects to my application.
the socket stays open until it is disconnected by the device.
The application must be able to send to or receive from the device at any time, full duplex. Neither operation can block or depend on the other.

This seems like something that would be common, but I can't seem to find a good enough example or thread here on Bytes to get me going in the right direction. Can anyone hep?
Jan 24 '12 #1
1 4300
After I posted, I figured it out - and, of course, it wasn't that hard. For anyone that got stuck like me, it is below. Any issues with doing it this way?


Expand|Select|Wrap|Line Numbers
  1.     class Com
  2.     {
  3.         TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 50000);
  4.         TcpClient tcpClient;
  5.         NetworkStream clientStream;
  6.  
  7.         public Com()
  8.         {
  9.             tcpListener.Start();
  10.             tcpClient = tcpListener.AcceptTcpClient();
  11.             clientStream = tcpClient.GetStream();
  12.             Thread Reader = new Thread(new ThreadStart(SocketRead));
  13.             Reader.IsBackground = true;
  14.             Reader.Start();
  15.             Reader.Join();
  16.         }
  17.  
  18.         private void SocketSend(string data)
  19.         {
  20.  
  21.             try
  22.             {
  23.                 ASCIIEncoding encoder = new ASCIIEncoding();
  24.                 byte[] message = encoder.GetBytes(data);
  25.                 clientStream.Write(message, 0, message.Length);
  26.                 clientStream.Flush();
  27.                 Console.WriteLine(data + " sent");
  28.             }
  29.             catch
  30.             {
  31.  
  32.             }
  33.             return;
  34.         }
  35.  
  36.         private void SocketRead()
  37.         {
  38.             bool listening = true;
  39.             while (listening)
  40.             {
  41.                 byte[] message = new byte[4096];
  42.                 int bytesRead;
  43.                 while (true)
  44.                 {
  45.                     bytesRead = 0;
  46.                     try
  47.                     {
  48.                         bytesRead = clientStream.Read(message, 0, 4096);
  49.                     }
  50.                     catch
  51.                     {
  52.                         break;
  53.                     }
  54.  
  55.                     if (bytesRead == 0)
  56.                     {
  57.                         break;
  58.                     }
  59.                     ASCIIEncoding encoder = new ASCIIEncoding();
  60.                     string received = encoder.GetString(message, 0, bytesRead);
  61.                     Console.WriteLine(received + " received");
  62.                     Thread Sender = new Thread(() => SocketSend(received));
  63.                     Sender.Start();
  64.                 }
  65.             }
  66.         }
  67.     }

and an easy client for it in Python

Expand|Select|Wrap|Line Numbers
  1. import socket
  2.  
  3. class Client:
  4.     def __init__(self):
  5.         self.Sender()
  6.  
  7.     def Sender(self):
  8.         host = 'localhost'
  9.         port = 50000
  10.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  11.         s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  12.         s.connect((host, port))
  13.  
  14.         while True:
  15.             data = raw_input("Send to Server>> ")
  16.             s.send(data)
  17.             data = s.recv(1024)
  18.             if data == "exit":
  19.                 break
  20.             print data
  21.         s.close()
  22.  
  23. Client()
  24.  
Jan 24 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Brandon | last post by:
Java seems to have taken off as the platform and language of choice for many embedded devices. Would it be feasible for Python(perhaps running on an embedded version of Linux) to act in such a...
3
by: Premshree Pillai | last post by:
For the uninitiated: "Socket Programming in Python" at evolt.org: http://evolt.org/article/Socket_Programming_in_Python/17/60276/index.html ===== -Premshree http://www.qiksearch.com/] ...
1
by: Tim Black | last post by:
My application requires sending a large piece (~2MB) of data to several devices on a network via TCP sockets. I have experimented with different methods for doing this and this has raised some...
3
by: Sham Yemul | last post by:
Hello, I recently started development in Vb.net. I am about to finish a product in VB.net Database Applicatio, Sql Server as Backend. I read little about wireless technology and PDAs. Is it...
18
by: Bud Cookson | last post by:
We are in the process of developing the requirements for a new medical device and the question has been raised about what development tool/language should be used. The application(s) will be...
4
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application...
0
by: Macca | last post by:
Hi, My app has an asynchronous socket server to receive and transmit data over ethernet connections coming in through a switch. My App will handle concurrent data for possibly 20+ embedded C...
1
by: Lina | last post by:
Hi all, am doing Client/Server application using Socket class, then i need to analysis the packet to retrieve the header for each packet, i read in some resources that i can do it using...
7
by: Shoveler | last post by:
I'm trying to send an ARP to determine different devices on the network. I need to see the MAC address of my devices on my LAN. With the MAC I can determine if I need to talk to that devices. I...
9
by: Hao | last post by:
We are doing very intensive network communication. We collect data from thousands of electric devices every minutes. The devices understand both socket and web service. They are either embeded...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.