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
Related
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.
I had a perfectly fine working console program that uses UdpClient.send to send messages to another program on the localhost (over port 7777). (which oddly enough is an almost identical version this C# script, but running in unity3d, and it has no trouble receiving with the same code).
Now I need to get replies from that program. I added a thread (see bottom) which listens on port 7778 for messages. But I am getting an error when starting saying that:
An existing connection was forcibly closed by the remote host
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Blaster
{
class Blaster
{
UdpClient client;
IPEndPoint outPoint;
IPEndPoint inPoint;
public int oPort = 7777;
public int iPort = 7778;
public string hostName = "localhost";
public int stepNum = 0;
const int rate = 1000;
public System.Timers.Timer clock;
Thread listener;
static void Main(string[] args)
{
Blaster b = new Blaster();
b.run();
}
Blaster()
{
client = new UdpClient();
outPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], oPort);
inPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], iPort);
}
void run()
{
this.stepNum = 0;
listener = new Thread(new ThreadStart(translater));
listener.IsBackground = true;
listener.Start();
Console.WriteLine("Press Enter to do a send loop...\n");
Console.ReadLine();
Console.WriteLine("started at {0:HH:mm:ss.fff}", DateTime.Now);
start();
Console.WriteLine("Press Enter to stop");
Console.ReadLine();
stop();
client.Close();
}
void stop()
{
clock.Stop();
clock.Dispose();
}
void start()
{
clock = new System.Timers.Timer(rate);
clock.Elapsed += send;
clock.AutoReset = true;
clock.Enabled = true;
}
void send(Object source, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("sending: {0}", stepNum);
Byte[] sendBytes = Encoding.ASCII.GetBytes(message());
try
{
client.Send(sendBytes, sendBytes.Length, outPoint);
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
string message()
{
Packet p = new Packet();
p.id = "car";
p.start = DateTime.Now;
p.x = 1.2f;
p.y = 0.4f;
p.z = 4.5f;
p.step = stepNum++;
string json = JsonConvert.SerializeObject(p);
return json;
}
void translater()
{
Byte[] data = new byte[0];
client.Client.Bind(inPoint);
while (true)
{
try
{
data = client.Receive(ref inPoint);
}
catch (Exception err)
{
Console.WriteLine("Blaster.translater: recieve data error: " + err.Message);
client.Close();
return;
}
string json = Encoding.ASCII.GetString(data);
Console.WriteLine(json);
Packet p = JsonConvert.DeserializeObject<Packet>(json);
}
}
}
}
Ok, I had seen some examples of folks using a single client object for both send and receive (as well as the same port). But then I saw a different port was needed if they were on the same host. Now I see you need a separate udpClient.
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Blaster
{
class Blaster
{
UdpClient client;
IPEndPoint outPoint;
IPEndPoint inPoint;
public int oPort = 7777;
public int iPort = 7778;
public string hostName = "localhost";
public int stepNum = 0;
const int rate = 1000;
public System.Timers.Timer clock;
Thread listener;
static void Main(string[] args)
{
Blaster b = new Blaster();
b.run();
}
Blaster()
{
client = new UdpClient();
outPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], oPort);
inPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], iPort);
}
void run()
{
this.stepNum = 0;
listener = new Thread(new ThreadStart(translater));
listener.IsBackground = true;
listener.Start();
Console.WriteLine("Press Enter to do a send loop...\n");
Console.ReadLine();
Console.WriteLine("started at {0:HH:mm:ss.fff}", DateTime.Now);
start();
Console.WriteLine("Press Enter to stop");
Console.ReadLine();
stop();
client.Close();
}
void stop()
{
clock.Stop();
clock.Dispose();
}
void start()
{
clock = new System.Timers.Timer(rate);
clock.Elapsed += send;
clock.AutoReset = true;
clock.Enabled = true;
}
void send(Object source, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("sending: {0}", stepNum);
Byte[] sendBytes = Encoding.ASCII.GetBytes(message());
try
{
client.Send(sendBytes, sendBytes.Length, outPoint);
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
string message()
{
Packet p = new Packet();
p.id = "car";
p.start = DateTime.Now;
p.x = 1.2f;
p.y = 0.4f;
p.z = 4.5f;
p.step = stepNum++;
string json = JsonConvert.SerializeObject(p);
return json;
}
void translater()
{
UdpClient server = new UdpClient();
Byte[] data = new byte[0];
server.Client.Bind(inPoint);
while (true)
{
try
{
data = server.Receive(ref inPoint);
}
catch (Exception err)
{
Console.WriteLine("Blaster.translater: recieve data error: " + err.Message);
client.Close();
return;
}
string json = Encoding.ASCII.GetString(data);
Console.WriteLine(json);
Packet p = JsonConvert.DeserializeObject<Packet>(json);
}
}
}
}
I want my computer to be a bluetooth server, handlig at least 100 connections from smartphones simultaneously. This is the idea:
I start the server and it begin to listen for connections. For each connection it should store the mac adress of the device. Each device should be able to send messages to the server and vice versa.
I've been searching a lot but didnt find a certain way.
How to listen for connections and handle them? Store in array? Start A Thread?
I've been able to start a 1 client server, but coudnt evolve it.
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.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
namespace BluetoothChamada
{
public partial class Form1 : Form
{
List<string> items;
String clientConectedName, clientConectedMAC;
public Form1()
{
InitializeComponent();
items = new List<string>();
}
private void bGo_Click(object sender, EventArgs e)
{
if (serverStarted)
{
updateUI("---Servidor já foi Iniciado---");
return;
}
if (rbServer.Checked)
{
connectAsServer();
}
else
{
Scan();
}
}
private void startScan()
{
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(Scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void Scan()
{
updateUI("Procurando dispositivos...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Procura finalizada");
updateUI(devices.Length.ToString() + " dispositivos encontrados");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void connectAsServer()
{
Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerThread.Start();
}
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
bool serverStarted = false;
public void ServerConnectThread()
{
serverStarted = true;
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
updateUI("---Servidor Iniciado, aguardando clientes---\r\n\n");
BluetoothClient connection = blueListener.AcceptBluetoothClient();
getData();
updateUI("Cliente: " + clientConectedName + "\r\nMac: " + clientConectedMAC);
Stream mStream = connection.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI(System.Environment.NewLine + "Recebido: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("FeedBack: OK \r\n");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exception)
{
updateUI("Cliente foi desconectado");
break;
}
}
}
private void getData()
{
BluetoothClient client = new BluetoothClient();
BluetoothDeviceInfo[] devices = client.DiscoverDevices();
foreach (BluetoothDeviceInfo device in devices)
{
if (!device.Connected)
{
}
else
{
clientConectedName = device.DeviceName;
clientConectedMAC = device.DeviceAddress.ToString();
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
}
}
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?
I am new to AT commands. I am using Nokia E71 to send and receive SMS. I am designing an application for sending SMS, but my code is not working.
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.IO.Ports;
using System.Threading;
namespace AT_commands
{
public partial class Form1 : Form
{
SerialPort serialPort;
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
this.serialPort = new SerialPort();
this.serialPort.PortName = "COM23";
this.serialPort.BaudRate = 9600;
this.serialPort.Parity = Parity.None;
this.serialPort.DataBits = 8;
this.serialPort.StopBits = StopBits.One;
this.serialPort.Handshake = Handshake.RequestToSend;
this.serialPort.DtrEnable = true;
this.serialPort.RtsEnable = true;
this.serialPort.NewLine = System.Environment.NewLine;
send_sms();
}
public bool send_sms()
{
label1.Text = "Loaded Successfuly";
String SMSMessage = "Message to send";
String CellNumber = "+923333333333";
String messageToSend = null;
if (SMSMessage.Length <= 160)
{
messageToSend = SMSMessage;
}
else
{
messageToSend = SMSMessage.Substring(0, 160);
}
if (this.IsOpen == true)
{
this.serialPort.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(SMSMessage + (char)(26));
return true;
}
return false;
}
public void Open()
{
if (this.IsOpen == false)
{
this.serialPort.Open();
}
}
public void Close()
{
if (this.IsOpen == true)
{
this.serialPort.Close();
}
}
public bool IsOpen
{
get
{
return this.serialPort.IsOpen;
}
}
public void Dispose()
{
if (this.IsOpen)
this.Close();
}
}
}
Please help me with this code!
Here's my code
using System;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
namespace CSharp_SMS
{
public partial class Form_SMS_Sender : Form
{
private SerialPort _serialPort;
public Form_SMS_Sender()
{
InitializeComponent();
}
private void buttonSend_Click(object sender, EventArgs e)
{
string number = textBoxNumber.Text;
string message = textBoxMessage.Text;
//Replace "COM7"withcorresponding port name
_serialPort = new SerialPort("COM7", 115200);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.Write("AT+CMGF=1\r");
Thread.Sleep(1000);
_serialPort.Write("AT+CMGS=\"" + number + "\"\r\n");
Thread.Sleep(1000);
_serialPort.Write(message + "\x1A");
Thread.Sleep(1000);
labelStatus.Text = "Status: Message sent";
_serialPort.Close();
}
}
}
Here's a link http://circuitfreak.blogspot.com/2013/03/c-programming-sending-sms-using-at.html
Why dont you open the port connection in the form_load() itself, later you can close it at the end as you did.
And do these too in Form_Load():
string cmd = "AT";
port.WriteLine(cmd + "\r");
port.Write(cmd + "\r");
port.WriteLine("AT+CMGF=1");
And simplifying the sms sending code:
port.WriteLine("AT+CMGS=\"" + PhNumber + "\"");
port.Write(Message + char.ConvertFromUtf32(26));
Try it this way.. You are not opening the connection to the serial port. I have tried it and it is working fine for me.
private void button1_Click(object sender, EventArgs e)
{
this.serialPort = new SerialPort();
this.serialPort.PortName = "COM5";
this.serialPort.BaudRate = 9600;
this.serialPort.Parity = Parity.None;
this.serialPort.DataBits = 8;
this.serialPort.StopBits = StopBits.One;
this.serialPort.Handshake = Handshake.RequestToSend;
this.serialPort.DtrEnable = true;
this.serialPort.RtsEnable = true;
this.serialPort.NewLine = System.Environment.NewLine;
serialPort.Open();
send_sms();
}
public bool send_sms()
{
String SMSMessage = "gsm MESSAGE FROM .NET C#";
String CellNumber = "+9233333333333";
String messageToSend = null;
if (SMSMessage.Length <= 160)
{
messageToSend = SMSMessage;
}
else
{
messageToSend = SMSMessage.Substring(0, 160);
}
if (serialPort.IsOpen)
{
this.serialPort.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(SMSMessage + (char)(26));
return true;
}
return false;
}