I'm trying to get data from a medical BT device that I already have pairing code and communication protocol.
Looking for some code I've got this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net.Sockets;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Windows.Forms;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;
namespace dConsoleApp
{
static class Program
{
// My BT USB adapter
private static BluetoothEndPoint EP = new BluetoothEndPoint(BluetoothAddress.Parse("00:02:72:CD:9A:33"), BluetoothService.BluetoothBase);
private static BluetoothClient BC = new BluetoothClient(EP);
// The BT device that would connect
private static BluetoothDeviceInfo BTDevice = new BluetoothDeviceInfo(BluetoothAddress.Parse("94:21:97:60:07:C0"));
private static NetworkStream stream = null;
static void Main(string[] args)
{
if (BluetoothSecurity.PairRequest(BTDevice.DeviceAddress, MY_PAIRING_CODE))
{
Console.WriteLine("PairRequest: OK");
if (BTDevice.Authenticated)
{
Console.WriteLine("Authenticated: OK");
BC.SetPin(MY_PAIRING_CODE);
BC.BeginConnect(BTDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), BTDevice);
}
else
{
Console.WriteLine("Authenticated: No");
}
}
else
{
Console.WriteLine("PairRequest: No");
}
Console.ReadLine();
}
private static void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
// client is connected now :)
Console.WriteLine(BC.Connected);
stream = BC.GetStream();
if (stream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (stream.DataAvailable);
// Print out the received message to the console.
Console.WriteLine("You received the following message : " + myCompleteMessage);
}
else
{
Console.WriteLine("Sorry. You cannot read from this NetworkStream.");
}
Console.ReadLine();
}
}
}
}
And this is the console result:
While I expect something like 0XA5 0x05 0x04 0x01 etc. etc.
Can you help me to get the correct result?
You want to replace the following:
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
with
for (int i = 0; i < numberOfBytesRead; i++)
myCompleteMessage.AppendFormat("0x{0:X2} ", myReadBuffer[i]);
Related
Server(GUI).png
Server ( GUI )
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Server_ProfiChat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static readonly object _lock = new object();
static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();
public static void handle_clients(object o)
{
int id = (int)o;
TcpClient client;
lock (_lock) client = list_clients[id];
while (true)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);
if (byte_count == 0)
{
break;
}
string data = Encoding.ASCII.GetString(buffer, 0, byte_count);
broadcast(data);
Console.WriteLine(data);
//var chatline = txtChat.Text;
Form1 formObj = new Form1();
formObj.txtChat.Text += data;
}
lock (_lock) list_clients.Remove(id);
client.Client.Shutdown(SocketShutdown.Both);
client.Close();
}
public static void broadcast(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data + Environment.NewLine);
lock (_lock)
{
foreach (TcpClient c in list_clients.Values)
{
NetworkStream stream = c.GetStream();
stream.Write(buffer, 0, buffer.Length);
}
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
int count = 1;
string serverIP = txtServerIP.Text;
int serverPort = Int32.Parse(txtServerPort.Text);
TcpListener ServerSocket = new TcpListener(IPAddress.Parse(serverIP), serverPort);
ServerSocket.Start();
while (true)
{
TcpClient client = ServerSocket.AcceptTcpClient();
lock (_lock) list_clients.Add(count, client);
Console.WriteLine("Someone connected!!");
Thread t = new Thread(handle_clients);
t.Start(count);
count++;
}
}
}
}
Server ( Console )
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace testServ
{
class Program
{
static readonly object _lock = new object();
static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();
static void Main(string[] args)
{
int count = 1;
TcpListener ServerSocket = new TcpListener(IPAddress.Parse("192.168.0.169"), 123);
ServerSocket.Start();
while (true)
{
TcpClient client = ServerSocket.AcceptTcpClient();
lock (_lock) list_clients.Add(count, client);
Console.WriteLine("Someone connected!!");
Thread t = new Thread(handle_clients);
t.Start(count);
count++;
}
}
public static void handle_clients(object o)
{
int id = (int)o;
TcpClient client;
lock (_lock) client = list_clients[id];
while (true)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);
if (byte_count == 0)
{
break;
}
string data = Encoding.ASCII.GetString(buffer, 0, byte_count);
broadcast(data);
Console.WriteLine(data);
}
lock (_lock) list_clients.Remove(id);
client.Client.Shutdown(SocketShutdown.Both);
client.Close();
}
public static void broadcast(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data + Environment.NewLine);
lock (_lock)
{
foreach (TcpClient c in list_clients.Values)
{
NetworkStream stream = c.GetStream();
stream.Write(buffer, 0, buffer.Length);
}
}
}
}
}
Client (console)
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace test_Clie
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("192.168.0.166");
int port = 123;
TcpClient client = new TcpClient();
client.Connect(ip, port);
Console.WriteLine("client connected!!");
NetworkStream ns = client.GetStream();
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
string s;
while (!string.IsNullOrEmpty((s = Console.ReadLine())))
{
byte[] buffer = Encoding.ASCII.GetBytes(s);
ns.Write(buffer, 0, buffer.Length);
}
client.Client.Shutdown(SocketShutdown.Send);
thread.Join();
ns.Close();
client.Close();
Console.WriteLine("disconnect from server!!");
Console.ReadKey();
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
Console.Write(Encoding.ASCII.GetString(receivedBytes, 0, byte_count));
Console.Write(ns);
}
}
}
}
Im a beginner but to me it seems to have to do with the threading?
Also because it freezes I cant see if the rest is working, any ideas on how to improve workflow, as in searching for the exact point the mistakes are? Im wasting alot of time searching anything because I dont know how to properly test, debug and pinpoint the mistakes I made.
Appreciate any help =))
Streams generally do exactly what you ask of them. If you ask for 10 bytes, then a Read will not return until there are 10 bytes to return. What stream.Read will not do, is return fewer bytes just because that is how many have been received.
This code will block until 1024 bytes have been read.
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);
if (byte_count == 0)
{
break;
}
Is that what you are expecting?
Generally, byte based protocols have a header, which contains how many bytes are in the payload.
Imagine the protocol below:
<stx><soh><len><eoh><payload><etx>
stx = Start of transmission
soh = Start of header
len = length of payload
eoh = End of header
etx = End of transmission
To read a complete packet you MUST read 4 bytes, and then you MUST read enough bytes to complete the payload, then the last byte should be ETX.
byte[5] header;
stream.Read(buffer, 0, 4);
int payloadLength = header[2];
byte[] payload = new byte[payloadLength];
stream.Read(payload, 0, payloadLength);
stream.Read() == ETX;
The TcpListener.AcceptTcpClient method is blocking. You could try using its asynchronous counterpart instead, combined with async/await:
private async void btnConnect_Click(object sender, EventArgs e)
{
/* ... */
TcpClient client = await ServerSocket.AcceptTcpClientAsync();
/* ... */
}
I am receiving data from streaming of bytes.
Code of TCPListerner :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 6054);
tcpListener.Start();
Console.WriteLine("Waiting for a client to connect...");
//blocks until a client connects
Socket socketForClient = tcpListener.AcceptSocket();
Console.WriteLine("Client connected");
//Read data sent from client
NetworkStream networkStream = new NetworkStream(socketForClient);
int bytesReceived, totalReceived = 0;
string fileName = "testing.txt";
byte[] receivedData = new byte[10000];
do
{
bytesReceived = networkStream.Read
(receivedData, 0, receivedData.Length);
totalReceived += bytesReceived;
Console.WriteLine("Total bytes read: " + totalReceived.ToString());
if (!File.Exists(fileName))
{
using (File.Create(fileName)) { };
}
using (var stream = new FileStream(fileName, FileMode.Append))
{
stream.Write(receivedData, 0, bytesReceived);
}
}
while (bytesReceived != 0);
Console.WriteLine("Total bytes read: " + totalReceived.ToString());
socketForClient.Close();
Console.WriteLine("Client disconnected...");
Console.ReadLine();
}
}
I want to add functionality to process only that message which is coming from streaming starting with <Product> and want to check when the message ends. For end we can use </Products>.
How to perform this validation check in existing code, Any Idea ?
I am using below code to send sample data into stream of bytes and is working perfectly fine.
CODE Used
CLIENT
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("localHost", 5200);
NetworkStream networkStream = tcpClient.GetStream();
BufferedStream bs = new BufferedStream(networkStream);
//Send data to listener
byte[] dataToSend = new byte[100];
new Random().NextBytes(dataToSend);
for (int i = 0; i < 100; i++)
networkStream.Write(dataToSend, 0, dataToSend.Length);
//when the network stream is closed, it also shuts down the connection
networkStream.Close();
Console.WriteLine("Done");
Console.ReadLine();
}
}
SERVER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(ip, 5200);
tcpListener.Start();
Console.WriteLine("Waiting for a client to connect...");
//blocks until a client connects
Socket socketForClient = tcpListener.AcceptSocket();
Console.WriteLine("Client connected");
//Read data sent from client
NetworkStream networkStream = new NetworkStream(socketForClient);
int bytesReceived, totalReceived = 0;
byte[] receivedData = new byte[1000];
do
{
bytesReceived = networkStream.Read
(receivedData, 0, receivedData.Length);
totalReceived += bytesReceived;
}
while (bytesReceived != 0);
Console.WriteLine("Total bytes read: " + totalReceived.ToString());
socketForClient.Close();
Console.WriteLine("Client disconnected...");
Console.ReadLine();
}
}
I don't know how to send the data from a file which can be of very large size in the same way.
I tried the below code but it is not working if size of file is 30MB or more.
public void SendTCP(string filePath, string IPA, Int32 PortN)
{
byte[] SendingBuffer = null;
TcpClient client = null;
lblStatus.Text = "";
NetworkStream netstream = null;
try
{
client = new TcpClient(IPA, PortN);
lblStatus.Text = "Connected to the Server...\n";
netstream = client.GetStream();
FileStream Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(BufferSize)));
progressBar1.Maximum = NoOfPackets;
int TotalLength = (int)Fs.Length, CurrentPacketLength, counter = 0;
for (int i = 0; i < NoOfPackets; i++)
{
if (TotalLength > BufferSize)
{
CurrentPacketLength = BufferSize;
TotalLength = TotalLength - CurrentPacketLength;
}
else
CurrentPacketLength = TotalLength;
SendingBuffer = new byte[CurrentPacketLength];
Fs.Read(SendingBuffer, 0, CurrentPacketLength);
netstream.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
if (progressBar1.Value >= progressBar1.Maximum)
progressBar1.Value = progressBar1.Minimum;
progressBar1.PerformStep();
}
lblStatus.Text = lblStatus.Text + "Sent " + Fs.Length.ToString() + " bytes to the server";
Fs.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
netstream.Close();
client.Close();
}
}
It should be as easy as this:
// Pass a file and send it through a socket.
static async Task SendFile(FileInfo file, Socket socket)
{
using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
using (var fileStream = file.OpenRead())
{
await fileStream.CopyToAsync(networkStream);
await networkStream.FlushAsync();
}
}
// Pass a socket and read the content to copy it to a file.
static async Task ReceiveFile(Socket socket, FileInfo file)
{
using (var fileStream = file.OpenWrite())
using (var networkStream = new NetworkStream(socket, false))
{
await networkStream.CopyToAsync(fileStream);
}
}
If you need to report the progress, you can use buffers and report the amount of bytes copied over:
static async Task SendFile(FileInfo file, Socket socket)
{
var readed = -1;
var buffer = new Byte[4096];
using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
using (var fileStream = file.OpenRead())
{
while(readed != 0)
{
readed = fileStream.Read(buffer, 0, buffer.Length);
networkStream.Write(buffer, 0, readed);
Console.WriteLine("Copied " + readed);
}
await networkStream.FlushAsync();
}
}
static async Task ReceiveFile(Socket socket, FileInfo file)
{
var readed = -1;
var buffer = new Byte[4096];
using (var fileStream = file.OpenWrite())
using (var networkStream = new NetworkStream(socket, false))
{
while (readed != 0)
{
readed = networkStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, readed);
Console.WriteLine("Copied " + readed);
}
}
}
Receiving bytes here in this code(server)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
namespace ByteLengthReading
{
class Program
{
static void Main(string[] args)
{
StartServer();
}
private static TcpListener _listener;
public static void StartServer()
{
IPAddress localIPAddress = IPAddress.Parse("119.43.29.182");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8001);
_listener = new TcpListener(ipLocal);
_listener.Start();
WaitForClientConnect();
}
private static void WaitForClientConnect()
{
object obj = new object();
_listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
Console.In.ReadLine();
}
private static void OnClientConnect(IAsyncResult asyn)
{
try
{
TcpClient clientSocket = default(TcpClient);
clientSocket = _listener.EndAcceptTcpClient(asyn);
HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
clientReq.StartClient();
}
catch (Exception ex)
{
throw ex;
}
WaitForClientConnect();
}
public class HandleClientRequest
{
TcpClient _clientSocket;
NetworkStream _networkStream = null;
public HandleClientRequest(TcpClient clientConnected)
{
this._clientSocket = clientConnected;
}
public void StartClient()
{
_networkStream = _clientSocket.GetStream();
WaitForRequest();
}
public void WaitForRequest()
{
byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];
_networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
private void ReadCallback(IAsyncResult result)
{
NetworkStream networkStream = _clientSocket.GetStream();
byte[] buffer = new byte[16384];
int read = -1;
int totRead = 0;
using (FileStream fileStream = new FileStream(#"C:\Foo" + Guid.NewGuid().ToString("N") + ".txt", FileMode.Create))
{
while ((read = networkStream.Read(buffer, 0, buffer.Length)) > 0)
{
totRead += read;
fileStream.Write(buffer, 0, read);
Console.WriteLine("Total Read" + totRead);
//fileStream.Write(buffer, 0, totRead);
//fileStream.Close();
}
fileStream.Close();
}
}
}
}
Sending bytes (Client), Sending bytes of length 4047810. But the abover server code is recieving only 4039618 bytes. Please help someone. Don't know y? At the time of reading last set of data it is coming out of the while loop. Please test this code and tell me where the problem lies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
using System.Threading;
namespace ByteLengthSending
{
class Program
{
static void Main(string[] args)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("119.43.29.182"), 8001);
//IPAddress ipAd = IPAddress.Parse("119.43.29.182");
//TcpClient client = new TcpClient(ipAd.ToString(), 8001);
//NetworkStream stream = client.GetStream();
int totread = 0;
byte[] longBuffer = new byte[3824726];
byte[] buffer = new byte[4096];
using (var fileStream = File.OpenRead("C:/Foo.txt"))
{
while (true)
{
int read = fileStream.Read(buffer, 0, buffer.Length);
totread += read;
if (read <= 0)
{
break;
}
for (int sendBytes = 0; sendBytes < read; sendBytes += client.Send(buffer, sendBytes, read - sendBytes, SocketFlags.None))
{
}
}
}
client.Close();
Console.WriteLine("Total Read" + totread);
Console.In.ReadLine();
}
}
}
Here is a sample which uses my library Griffin.Framework to transmit a file (Apache license).
All you need to do is to install the nuget package "griffin.framework" and then create a console application and replace Program class with the following:
class Program
{
static void Main(string[] args)
{
var server = new ChannelTcpListener();
server.MessageReceived = OnServerReceivedMessage;
server.Start(IPAddress.Any, 0);
var client = new ChannelTcpClient<object>(new MicroMessageEncoder(new DataContractMessageSerializer()),
new MicroMessageDecoder(new DataContractMessageSerializer()));
client.ConnectAsync(IPAddress.Loopback, server.LocalPort).Wait();
client.SendAsync(new FileStream("TextSample.txt", FileMode.Open)).Wait();
Console.ReadLine();
}
private static void OnServerReceivedMessage(ITcpChannel channel, object message)
{
var file = (Stream) message;
var reader = new StreamReader(file);
var fileContents = reader.ReadToEnd();
Console.WriteLine(fileContents);
}
}
The library can send/receive any type of stream of any size (as long as the size is known). The client will automatically create a MemoryStream or FileStream depending on the stream size.
I am trying to build a basic server client application in winforms. However the server does nothing. Just sort of opens up and hangs if i may say so. What am i doing wrong. I made the application as follows:
The Server Winform
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace ServerWinForms
{
public partial class Form1 : Form
{
public delegate void AddText(TcpClient tcp, RichTextBox rtb);
public AddText myDelegate;
Thread myThread;
public Form1()
{
InitializeComponent();
myDelegate = new AddText(ClientSession);
}
void begin(Object obj)
{
var loaclAddress = IPAddress.Parse("127.0.0.1");
var tcpListener = new TcpListener(loaclAddress, 81);
tcpListener.Start();
while (true)
{
var tcpClient = tcpListener.AcceptTcpClient();
Form1 myForm1 = (Form1)obj;
myForm1.Invoke(myForm1.myDelegate);
//rtb.AppendText("Waiting for connection ");
// Console.WriteLine("Waiting for a connection");
//rtb.AppendText("Client Accepted ");
//Console.WriteLine("Client Accepted");
/*Thread thread = new Thread(() => ClientSession(tcpClient))
{
IsBackground = true
};
thread.Start();
//Console.WriteLine("Client Session thread started");
*/
}
}
private static bool tryRead(Stream stream, byte[] buffer, int offset, int count)
{
int bytesRead;
while (count > 0 && (bytesRead = stream.Read(buffer, offset, count)) > 0)
{
offset += bytesRead;
count -= bytesRead;
}
return count == 0;
}
public static void ClientSession(TcpClient tcpClient, RichTextBox rtb)
{
const int totalByteBuffer = 4096;
byte[] buffer = new byte[256];
// UC ucObj = new UC();
using (var networkStream = tcpClient.GetStream())
using (var bufferedStream = new BufferedStream(networkStream, totalByteBuffer))
while (true)
{
if (!tryRead(bufferedStream, buffer, 0, 1))
{
break;
}
byte messageLen = buffer[0];
if (!tryRead(bufferedStream, buffer, 1, messageLen))
{
break;
}
var message = Encoding.ASCII.GetString(buffer, 1, messageLen);
//Console.WriteLine(/*"Message Recieved: {0}", */ message);
RichTextBox rcb = new RichTextBox();
rtb.AppendText(message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
myThread = new Thread(begin);
myThread.Start(this);
//begin();
}
}
}
The Client Winform (though i believe everything is in order here but still... )
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ClientWinForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private static byte[] msg2ByteArray(string message, Encoding enc)
{
var byteCount = enc.GetByteCount(message);
if (byteCount > byte.MaxValue)
{
throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
}
var byteArray = new byte[byteCount + 1];
byteArray[0] = (byte)byteCount;
enc.GetBytes(message, 0, message.Length, byteArray, 1);
return byteArray;
}
void sendMsg()
{
String message;
using (var tcpClient = new TcpClient())
{
tcpClient.Connect("127.0.0.1", 81);
using (var networkStream = tcpClient.GetStream())
using (var bufferedStream = new BufferedStream(networkStream))
{
//while (true)
//{
byte[] buffer = new byte[256];
//Console.WriteLine("Write Message");
message = richTextBox.Text;
var byteArray = msg2ByteArray(message, Encoding.ASCII);
bufferedStream.Write(byteArray, 0, byteArray.Length);
bufferedStream.Flush();
//}
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
sendMsg();
}
}
}
kewal, your code looks good and your program also. i also liked that you share all the code, it is most frustrating when i need to ask almost every other asked to do that.
now to the problem. you use tcpListener.Start(); in your server.
as we can read here:
"If a connection request is received, the Start method will queue
the request and continue listening for additional requests until you
call the Stop method"
i believe what you wanted is to use AcceptSocket() method - read
here
i can suggest: use different port. low number ports are taken
already and might not work. i think 81 if for http's, though i'm not
sure
EDIT
3. for the client use this MSDN example to see if the basic
example works for you