nodejs and c# combinationquery - c#

I am building an application , in which I need to have a c# server and nodejs client. I have built the components , but I am always getting ECONNREFUSED error. any leads when I can except this error?
FYI,
I am able to connect to c# server from c# client. similarly. I am able to connect to nodejs tcp server from nodejs tcp client. however the I am facing error with this mixture.
hey sorry for not adding code earlier.
the following is the c# server code:
using System;
using System.Text;
using AsyncClientServerLib.Server;
using System.Net;
using AsyncClientServerLib.Message;
using SocketServerLib.SocketHandler;
using SocketServerLib.Server;
namespace TestApp
{
delegate void SetTextCallback(string text);
public partial class FormServer : Form
{
private BasicSocketServer server = null;
private Guid serverGuid = Guid.Empty;
public FormServer()
{
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
if (this.server != null)
{
this.server.Dispose();
}
base.OnClosed(e);
}
private void buttonStart_Click(object sender, EventArgs e)
{
this.serverGuid = Guid.NewGuid();
this.server = new BasicSocketServer();
this.server.ReceiveMessageEvent += new SocketServerLib.SocketHandler.ReceiveMessageDelegate(server_ReceiveMessageEvent);
this.server.ConnectionEvent += new SocketConnectionDelegate(server_ConnectionEvent);
this.server.CloseConnectionEvent += new SocketConnectionDelegate(server_CloseConnectionEvent);
this.server.Init(new IPEndPoint(IPAddress.Loopback, 2147));
this.server.StartUp();
this.buttonStart.Enabled = false;
this.buttonStop.Enabled = true;
this.buttonSend.Enabled = true;
MessageBox.Show("Server Started");
}
void server_CloseConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is disconnected from the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is connected to the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ReceiveMessageEvent(SocketServerLib.SocketHandler.AbstractTcpSocketClientHandler handler, SocketServerLib.Message.AbstractMessage message)
{
BasicMessage receivedMessage = (BasicMessage)message;
byte[] buffer = receivedMessage.GetBuffer();
if (buffer.Length > 1000)
{
MessageBox.Show(string.Format("Received a long message of {0} bytes", receivedMessage.MessageLength), "Socket Server",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string s = System.Text.ASCIIEncoding.Unicode.GetString(buffer);
this.SetReceivedText(s);
}
private void buttonStop_Click(object sender, EventArgs e)
{
this.server.Shutdown();
this.server.Dispose();
this.server = null;
this.buttonStart.Enabled = true;
this.buttonStop.Enabled = false;
this.buttonStop.Enabled = false;
MessageBox.Show("Server Stopped");
}
private void SetReceivedText(string text)
{
if (this.textBoxReceived.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetReceivedText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBoxReceived.Text = text;
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
ClientInfo[] clientList = this.server.GetClientList();
if (clientList.Length == 0)
{
MessageBox.Show("The client is not connected", "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AbstractTcpSocketClientHandler clientHandler = clientList[0].TcpSocketClientHandler;
string s = this.textBoxSend.Text;
byte[] buffer = System.Text.ASCIIEncoding.Unicode.GetBytes(s);
BasicMessage message = new BasicMessage(this.serverGuid, buffer);
clientHandler.SendAsync(message);
}
}
}
The following is the nodejs client code.
var sys = require("sys"),
net = require("net");
var client = net.createConnection(2147);
client.setEncoding("UTF8");
client.addListener("connect", function() {
sys.puts("Client connected.");
// close connection after 2sec
setTimeout(function() {
sys.puts("Sent to server: close");
client.write("close", "UTF8");
}, 2000);
});
client.addListener("data", function(data) {
sys.puts("Response from server: " + data);
if (data == "close") client.end();
});
client.addListener("close", function(data) {
sys.puts("Disconnected from server");
});

I am able to solve the issue. This is just a overlook issue. In server code , I am using lan address assigned to my machine , but in client side , I am using 127.0.0.1 . when I changed the both to same value , I amnot getting econnrefused error.
Now I am able to send and receive data. However I am getting ECONNRESET error very frequently. any leads?

Related

Client Dissconnect or down

I have 2 Application in a visual studio Windows Forms App(.Net Framework 4) The names of my two programs are:
IpServer
IpClient
My problem is that I do not know what to do that when the IpClient Application closes or stops or the IpServer Application shows a message in messagebox.show("Client Is dissconnect")
IpServer Code:
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 IpServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpListener tcplist;
Socket s;
private void init()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
tcplist = new TcpListener(ip,5050);
tcplist.Start();
while (true)
{
s = tcplist.AcceptSocket();
Thread t = new Thread(new ThreadStart(replay));
t.IsBackground = true;
t.Start();
}
}
private void replay()
{
Socket sc = s;
NetworkStream ns = new NetworkStream(sc);
StreamReader reader = new StreamReader(ns);
StreamWriter writer = new StreamWriter(ns);
string str = "";
string response = "";
try { str = reader.ReadLine(); }
catch { str = "error"; }
if (str == "register")
{
MessageBox.Show("ok");
}
response = "registeredSucss,";
writer.WriteLine(response);
writer.Flush();
ns.Close();
sc.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(init));
t.IsBackground = true;
t.Start();
MessageBox.Show("Server run!!");
button1.Enabled = false;
}
and IpClient Code :
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 IpClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpClient tcp;
NetworkStream ns;
StreamReader reader;
StreamWriter writer;
string str = "";
private void button1_Click(object sender, EventArgs e)
{
try
{
tcp = new TcpClient("127.0.0.1",5050);
tcp.ReceiveBufferSize = 25000;
tcp.NoDelay = true;
ns = tcp.GetStream();
reader = new StreamReader(ns);
writer = new StreamWriter(ns);
writer.WriteLine("register");
writer.Flush();
str = reader.ReadLine();
string[] strsplit = null;
strsplit = str.Split(',');
if (strsplit[0] != "registeredSucss")
{
MessageBox.Show("Not connected");
}
else
{
MessageBox.Show("Your connected");
}
}
catch
{
MessageBox.Show("error");
}
}
I wrote a complete example for you.
You can modify it according to your needs.
Simply connecting the client to the server without sending or receiving messages will not disconnect.
In the server and the client, there is a thread that continuously calls the receive function, and sends a message when the connection is disconnected.
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0) {
///Write the desired operation
}
"Disconnect when closing the window" uses the formclosing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
}
This is the control diagram used by the two windows:
IpClient:
IpServe:
This is the code for the two windows:
IpClient:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace IpClient {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
Socket socket;//The socket responsible for the connection
private void ConnectB_Click(object sender, EventArgs e) {
//Determine whether to request a connection repeatedly
try {
Log("Connected " + socket.LocalEndPoint.ToString() + "\nPlease do not request the connection repeatedly");
} catch {
//Determine whether the input is wrong
try {
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Create IP address and port number;
IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Determine whether you can connect to the server
try {
socket.Connect(iPEndPoint);
Log("Connected " + socket.LocalEndPoint.ToString());
//Start receiving data thread
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
} catch {
Log("Port is not open");
}
} catch {
socket = null;
Log("Input error");
}
}
}
private void Log(string str) {
ClientLog.AppendText(str + "\r\n");
}
private void receive() {
while (true) {
//Determine whether the data can be received
try {
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0) {
Log("Port is not open");
CloseSocket(socket);
socket = null;
break;
}
string txt = Encoding.UTF8.GetString(buffer, 0, length);
Log(socket.RemoteEndPoint + ":\r\t" + txt);
} catch {
break;
}
}
}
private void Form1_Load(object sender, EventArgs e) {
Control.CheckForIllegalCrossThreadCalls = false;
}
private void CloseB_Click(object sender, EventArgs e) {
if (socket != null) {
CloseSocket(socket);
socket = null;
Log("Connection closed");
} else {
Log("Not connected");
}
}
private void SendB_Click(object sender, EventArgs e) {
try {
string txt = SendText.Text;
byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii encoding
socket.Send(buffer);
} catch {
Log("Not connected");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
if (socket != null) {
CloseSocket(socket);
socket = null;
}
}
//Disconnect socket
private void CloseSocket(Socket o) {
try {
o.Shutdown(SocketShutdown.Both);
o.Disconnect(false);
o.Close();
} catch {
Log("error");
}
}
}
}
IpServer:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace IpServer {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
Socket socketSend;//Socket responsible for communication
Socket socketListener;//Socket responsible for monitoring
Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();//Store the connected Socket
private void listnerB_Click(object sender, EventArgs e) {
//Create a listening socket
//SocketType.Stream streaming corresponds to the tcp protocol
//Dgram, datagram corresponds to UDP protocol
socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try {
//Create IP address and port number;
IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Let the listening socket bind the ip and port number
socketListener.Bind(iPEndPoint);
Log("Listen successfully" + ip + "\t" + port);
//Set up the listening queue
socketListener.Listen(10);//Maximum number of connections at a time
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socketListener);
} catch {
Log("Failed to listen");
}
}
//Use threads to receive data
private void Listen(object o) {
Socket socket = o as Socket;
while (true) {
//The socket responsible for monitoring is used to receive client connections
try {
//Create a socket responsible for communication
socketSend = socket.Accept();
dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());
clientCombo.SelectedIndex = clientCombo.Items.IndexOf(socketSend.RemoteEndPoint.ToString());
Log("Connected " + socketSend.RemoteEndPoint.ToString());
//Start a new thread to receive information from the client
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start(socketSend);
} catch {
continue;
}
}
}
//The server receives the message from the client
private void receive(object o) {
Socket socketSend = o as Socket;
while (true) {
//Try to connect to the client
try {
//After the client connects successfully, the server receives the message from the client
byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
//Number of valid bytes received
int length = socketSend.Receive(buffer);
if (length == 0) {
string tmpIp = socketSend.RemoteEndPoint.ToString();
Log(tmpIp + " Offline");
clientCombo.Items.Remove(tmpIp);
//Try to delete the connection information
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
CloseSocket(dictionary[tmpIp]);
dictionary.Remove(tmpIp);
break;
}
string str = Encoding.ASCII.GetString(buffer, 0, length);
Log(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
} catch {
break;
}
}
}
private void Log(string str) {
ServerLog.AppendText(str + "\r\n");
}
private void Form1_Load(object sender, EventArgs e) {
//Cancel errors caused by cross-thread calls
Control.CheckForIllegalCrossThreadCalls = false;
}
//Send a message
private void SendB_Click(object sender, EventArgs e) {
string txt = SendText.Text;
byte[] buffer = Encoding.UTF8.GetBytes(txt);
try {
string ip = clientCombo.SelectedItem.ToString();//Get the selected ip address
Socket socketsend = dictionary[ip];
socketsend.Send(buffer);
} catch{
Log("Transmission failed");
}
}
private void Close_Click(object sender, EventArgs e) {
try {
try {
string tmpip = socketSend.RemoteEndPoint.ToString();
CloseSocket(dictionary[tmpip]);
dictionary.Remove(tmpip);
clientCombo.Items.Remove(tmpip);
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
socketSend.Close();
Log(socketSend.RemoteEndPoint.ToString() + "Offline");
socketListener.Close();
Log("Listener is closed");
} catch{
socketListener.Close();
Log("Listener is closed");
}
} catch {
Log("close error");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
try {
try {
string tmpip = socketSend.RemoteEndPoint.ToString();
CloseSocket(dictionary[tmpip]);
dictionary.Remove(tmpip);
clientCombo.Items.Remove(tmpip);
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
socketSend.Close();
socketListener.Close();
} catch {
socketListener.Close();
}
} catch {
}
}
private void CloseSocket(Socket o) {
try {
o.Shutdown(SocketShutdown.Both);
o.Disconnect(false);
o.Close();
} catch {
Log(o.ToString() + "error");
}
}
}
}
OutPut:
Closing the window causes disconnection:
Disconnect manually:
Transfer data:
If you have any question about my code, please add a comment below.

ELM327 returns?

Iam developing a WPF application to interact with ELM327. The communication medium between myApp and ELM327 is USB protocol. ELM327 is connected to vehicle through OBD port. My app able to establish USB communication successfully. Whatever command Iam sending from my App, Iam getting ? as reply. I set baud rate as 9600. For example, I sent ATZ, iam getting ? as reply. I sent 010D, I got ?. I tried with the app comes along with ELM327, that app can successfully able to extract data.
MyApp USB communication connect code:
public SerialPort sport;
private void Button_Click(object sender, RoutedEventArgs e)
{
int baudValue=0;
if (cbBaud.Text == null)
MessageBox.Show("select a baud rate");
else
{
if (cbBaud.Text != null)
{
baudValue = int.Parse(cbBaud.Text);
}
serialConnect(baudValue);
}
}
public void serialConnect(int baudRate)
{
try
{
if (tbCOM.Text != null)
{
sport = new System.IO.Ports.SerialPort(tbCOM.Text,
baudRate);
if (!sport.IsOpen)
{
sport.Open();
sport.DataReceived += new SerialDataReceivedEventHandler(serialDataReceived);
elIndicator.Fill = Brushes.Green;
}
else
{
MessageBox.Show("Connection already Opened");
}
}
}
catch(Exception EX)
{
MessageBox.Show("Connection Error");
}
}
MyApp data sent code:
private void BtSent_Click(object sender, RoutedEventArgs e)
{
try
{
sport.WriteLine(tbSend.Text);
}
catch(Exception EX)
{
MessageBox.Show("Write Error");
}
}
MyApp data receive code:
private void serialDataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
recData.Text = "\n";
recData.Text = System.Environment.NewLine + sport.ReadExisting();
}));
}
Is there any initialization code amI have to sent ?

Using UdpClient, how do you retry UdpClient.Connect() until it succeeds?

My client/server programs work well with each other, but only when the server is up and running before my client starts. If the client fails to connect on the first try, I can't get it to try again.
Here's my Client's connect method.
public void connect()
{
IPAddress server_address = IPAddress.Parse("127.0.0.1");
IPEndPoint server_ip = new IPEndPoint(server_address, 5685);
Console.WriteLine("2");
bool connected = false;
while (!connected)
{
try
{
Console.WriteLine("IN CONNECTED");
udp_client.Connect(server_ip);
byte[] send_data = Encoding.ASCII.GetBytes("INIT");
udp_client.Send(send_data, send_data.Length);
byte[] received_bytes = udp_client.Receive(ref server_ip);
string received_data = Encoding.ASCII.GetString(received_bytes);
if (received_data == "INIT")
{
connected = true;
Console.WriteLine("RECEIVED INIT");
listen(server_ip);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
What I was hoping to see is the udp_client.Connect(server_ip) to loop until I received that "INIT" message from the server.
As it currently stands, there is no loop. It seems to get stuck on udp_client.Receive(ref server_ip).
Any help would be appreciated!
This is pseudoCode - you will have to move somethings to class scope to allow future send/receives (which you'd do using a different method). This is only designed to show you how to connect when the connection blocks:
bool isClientConnected = false;
var connector = new System.ComponentModel.BackgroundWorker();
public void connectToUDP(){
connector.DoWork+= connect;
connector.RunWorkerAsync();
}
private void connect(object sender, DoWorkEventArgs e)
{
IPAddress server_address = IPAddress.Parse("127.0.0.1");
IPEndPoint server_ip = new IPEndPoint(server_address, 5685);
Console.WriteLine("2");
try
{
Console.WriteLine("Waiting for server...");
udp_client.Connect(server_ip);
byte[] send_data = Encoding.ASCII.GetBytes("INIT");
udp_client.Send(send_data, send_data.Length);
byte[] received_bytes = udp_client.Receive(ref server_ip);
string received_data = Encoding.ASCII.GetString(received_bytes);
if (received_data == "INIT")
{
isClietConnected = true;
Console.WriteLine("now connected");
listen(server_ip);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public bool sendReceiveUDP(string send){
if(!isClientConnected){
return false;
}
//perform send
return true;
}
You would then maintain the connected session using class scope and send/receive using a different method. This is for connect only since you only need to do it once.
How you set something like this up:
private bool isConnected = false();
private bool send(){
if(!isConnected){
connect();
}
//send
}
private bool connect(){
if(!isConnected){
//launch connection thread
}
}
private delegate void onNewReceive(string message);
public event onNewReceive onNewReceiveEvent;
public void fireEvent(string message){
onNewReceiveEvent.Invoke(message);
}
private void waitForData(object sender, DoWorkEventArgs e){
//this is the backgroundworker
while(true){
receive();
fireEvent(message);
}
}
Then, subscribe to the onNewREceivedEvent in another class and process the inbound message. onNewReceivedEvent += processInboundMEsasage();
This is all psuedocode and "brain compiled" (creit to others) so it's only meant for demonstrations. Without intellisense, I'm lost.

TCPIP connection in c# and data sending/receiving in another threads

I have a problem with my TCPIP connection Form programm.
I have a code, where I'm trying to send and receive some data from server.
The main problem of my app is how to reconcile some threads:
myListenThread - to listening data from server
myReadStreamThread - to read data from server
System.Threading.Thread - main thread eg. to write data to server
captureThread - to do another things like capturing images from camera
Part of my code:
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
Connect();
Connected = true;
this.myListenThread = new Thread(new ThreadStart(Listen));
this.myListenThread.Start();
}
catch
{
MessageBox.Show("Invalid host! Try again.");
}
}
private void Listen()
{
this.myReadStreamThread = new Thread(new ThreadStart(ReadStream));
this.myReadStreamThread.Start();
while (Connected)
{
if (!myReadClient.Connected)
{
Connect();
}
}
}
private void Connect()
{
IPAddress IP = IPAddress.Parse(textboxIP.Text);
int PORT = Convert.ToInt32(textboxPORT.Text);
this.myReadClient = new TcpClient();
this.myReadClient.Connect(IP, PORT);//SOMETIMES HERE'S AN ERROR
this.myStream = this.myReadClient.GetStream();
Properties.Settings.Default.IP = Convert.ToString(IP);
Properties.Settings.Default.PORT = Convert.ToString(PORT);
Properties.Settings.Default.Save();
}
private void ReadStream()
{
while (true)
{
try
{
this.myReadBuffer = new byte[this.myReadClient.ReceiveBufferSize];
this.myBufferSize = myStream.Read(myReadBuffer, 0, this.myReadClient.ReceiveBufferSize);
if (myBufferSize != 0)
{
this.myString = Encoding.ASCII.GetString(myReadBuffer);
//myDelegate myDel;
//myDel = new myDelegate(Print);
//richtextboxRead.Invoke(myDel);
}
}
catch
{
break;
}
}
}
All is working correct when I'm connecting to server, but when I want to send some string the problem appears because of threads.
I decided to send string, by clicking Button3 and waiting until I receive string "1" from server using while loop:
private void button3_Click(object sender, EventArgs e)
{
this.captureThread = new Thread(new ThreadStart(() => this.newGame()));
this.captureThread.Start();
}
private bool newGame()
{
string command = "12345abc";
if (Connected)
{
WriteStream(command);
}
while (myBufferSize == 0 && myString !="1") { }
Thread.Sleep(2000);
...//doing other things
}
private void WriteStream(string command)
{
Connect();
this.myWriteBuffer = Encoding.ASCII.GetBytes(command);
this.myStream.Write(this.myWriteBuffer, 0, command.Length);
}
And the problem with connection and data send/receive problem appears, when it should write my string "command" - it doesn't react. MyBufferSize is always 0 and myString is always null. Sometimes an Error about connection appears when I click Button3 (assigned in code). I think it is because in captureThread I can't see any data from another threads. How to solve it?

C# client application doesn't receive messages from linux tcp server

Situation:
1. Linux TCP server
2 Windows C# client application
The server receives messages from client, but when I try to send messages from server to the client nothing happens. When I disconnect I get the error:
"Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall." and it points to the line ---> string Response = swRead.ReadLine();
Here is the Client code:
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;
using System.Threading;
namespace AsynClient
{
public partial class Form1 : Form
{
private TcpClient client;
private StreamWriter swSend;
private StreamReader swRead;
private bool connected = false;
string bojaTekst = "", bojaPoz = "";
private delegate void UpdateLogCallback(string strMessage);
private Thread thrMessag;
public Form1()
{
Application.ApplicationExit += new EventHandler(OnApplicationExit);
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (connected == false)
{
InitializeConnection();
}
else
MessageBox.Show("Vec je uspostavljenja konekcija.");
}
private void InitializeConnection()
{
client = new TcpClient();
client.Connect("192.168.100.82", 3456);
swSend = new StreamWriter(client.GetStream()); //prvo mora da se konektuje, pa onda ova komanda
thrMessag = new Thread(new ThreadStart(ReceiveMessages));
thrMessag.Start();
connected = true;
btnSend.Enabled = true;
btnDisconnect.Enabled = true;
txtMsg.Enabled = true;
btnConnect.Enabled = false;
}
private void UpdateLog(string strMessage)
{
txtServ.AppendText(strMessage + "\r\n");
}
private void ReceiveMessages()
{
swRead = new StreamReader(client.GetStream());
string Response = swRead.ReadLine();
while (connected)
{
// Show the messages in the log TextBox
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { swRead.ReadLine() });
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (listBoxTekst.SelectedIndex == -1)
listBoxTekst.SelectedIndex = 0;
if (listBoxPozadina.SelectedIndex == -1)
listBoxPozadina.SelectedIndex = 0;
bojaTekst = listBoxTekst.Text;
bojaPoz = listBoxPozadina.Text;
SendMessage();
}
private void SendMessage()
{
txtMsg.Text);
if (txtMsg.Lines.Length >= 1)
{
swSend.WriteLine(bojaPoz + "\t" + bojaTekst + "\t" + txtMsg.Text + "\t");
swSend.Flush();
txtMsg.Lines = null;
}
txtMsg.Text = "";
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
char[] quit = new char[5];
quit[0] = 'q'; quit[1] = 'w'; quit[2] = 'w'; quit[3] = 'w'; quit[4] = '\0';
connected = false;
btnConnect.Enabled = true;
btnSend.Enabled = false;
btnDisconnect.Enabled = false;
txtMsg.Enabled = false;
swSend.WriteLine(quit);
swSend.Flush();
swSend.Close();
client.Close();
}
public void OnApplicationExit(object sender, EventArgs e)
{
if (connected == true)
{
connected = false;
swSend.WriteLine("qwww"); //proveri da li radi f-ja kako treba
swSend.Flush();
swSend.Close();
client.Close();
}
}
}
}
The server side receives the messages with the read() function and it works fine, but when it sends with write() the C# client doesn't receive the message.
Just one thing (there mioght be other problems):
You have a connected variable, which value you set to true, after you start your listening thread. The loop within the thread doesnt even run once.
thrMessag = new Thread(new ThreadStart(ReceiveMessages));
thrMessag.Start();
connected = true; //here is your first bug, should come before the previos line

Categories