Server & Client Always Not responding - c#

I'm new to sockets so I tried to create a server and a client that exchange messages. I created one in C# but it gave me weird error which it once I start the server it freezes and "not responding" message appears ... same happens with client when I connect the server but the problem is when I close any of them .. the other application have the updates shown up so idk what the problem is anyways here are the codes U used
Server class
Socket Soc;
static ushort MaxClients = 1000;
static List<Socket> ClientList = new List<Socket>(MaxClients);
static bool ServerStarted;
public Server()
{
InitializeComponent();
button1.Enabled = false;
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e) // Send
{
string MessageToSend = textBox1.Text;
byte[] Buffer = Encoding.Default.GetBytes(MessageToSend);
foreach (var client in ClientList)
{
Soc.Send(Buffer, 0, Buffer.Length, SocketFlags.None);
}
textBox2.Text += " Message Sent To Clients : " + MessageToSend + Environment.NewLine;
}
private void button3_Click(object sender, EventArgs e) // Start
{
StartServer("25.21.113.163", 5000);
}
private void button2_Click(object sender, EventArgs e) // Stop
{
CloseServer();
}
private void button4_Click(object sender, EventArgs e) // Exit
{
CloseServer();
Application.Exit();
}
public void StartServer(string Ip, ushort Port)
{
Soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Soc.Bind(new IPEndPoint(IPAddress.Parse(Ip), Port));
textBox2.Text += " Server Is Created On Ip : " + Ip + ", Port : " + Port + Environment.NewLine;
Soc.Listen(MaxClients);
textBox2.Text += " Server Is Listening to Clients Now... " + Environment.NewLine;
ServerStarted = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
ReceiveData();
}
public void ReceiveData()
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}
}
public void CloseServer()
{
Soc.Close();
ServerStarted = false;
textBox2.Text += " Server Is Closed Now... " + Environment.NewLine;
button3.Enabled = true;
button2.Enabled = false;
button1.Enabled = false;
}
Client class
Socket Client;
public Form1()
{
InitializeComponent();
button1.Enabled = false;
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e) // Send
{
string MessageToSend = textBox2.Text;
byte[] Buffer = Encoding.Default.GetBytes(MessageToSend);
Client.Send(Buffer, 0, Buffer.Length, SocketFlags.None);
textBox1.Text += " Sent Message To Server Is : " + MessageToSend + Environment.NewLine;
}
private void button2_Click(object sender, EventArgs e) // LogOut
{
ClientClose();
}
private void button3_Click(object sender, EventArgs e) // Connect
{
ConnectToServer("25.21.113.163", 5000);
}
private void button4_Click(object sender, EventArgs e) // Exit
{
ClientClose();
Application.Exit();
}
public void ConnectToServer(string Ip, ushort Port)
{
try
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(Ip, Port);
textBox1.Text += " You Are Now Connected To Server Hosted On Ip : " + Client.RemoteEndPoint + Environment.NewLine;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
ReceiveData();
}
catch
{
textBox1.Text += " Server In Offline Now " + Environment.NewLine;
}
}
public void ReceiveData()
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedBytesLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string ReceivedMessage = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedBytesLength);
textBox1.Text += " Received Message From Server Is : " + ReceivedMessage + Environment.NewLine;
}
}
public void ClientClose()
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
Client.Dispose();
Client.Close();
textBox1.Text += " You Are Disconnected From Server" + Environment.NewLine;
}
I'd like to know what did I do wrong? And how can I get rid of that silly "Not Responding" state of both applications?

First, Let's make a corrections on your code so that it works, thank I'd give some Asynchronous Socket tutorials which is a lot easier than Synchronous.
Your problem is in this line:
public void ReceiveData()
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}
}
This is because of 2 reasons:
1) You must listen to incoming connection to a separate thread.
2) You must listen to each client in a separate thread too, so they don't block each other. In your example second while(true) which is listening for client is blocking server socket from accepting other clients. Refactor it to:
public void ReceiveData()
{
new Thread(() =>
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
new Thread(() =>
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}).Start();
}
}).Start();
}
This approach uses separate thread for each client to process received data from client.
I also added code for client app:
public void ReceiveData()
{
new Thread(() =>
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedBytesLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string ReceivedMessage = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedBytesLength);
textBox1.Text += " Received Message From Server Is : " + ReceivedMessage + Environment.NewLine;
}
}).Start();
}
In the future have a look Asynchronous Sockets and you will no more need handling multithreading issues.
http://msdn.microsoft.com/en-us/library/fx6588te.aspx
http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx
EDIT Updated client/ser

Related

C# Windows service - Run two void methods

Can anyone help me with Windows service in C#?
I used topshelf to create windows service. I have issue with run two methods together. When I run app via in console, it works. But when I try to run in windows service, it's don't work together like I need.
First I start communication with OPC DA server and second I want start TCP Listerner
public void Start()
{
try
{
T1 = new Thread(new ThreadStart(DoOpc));
T1.Start();
T2 = new Thread(new ThreadStart(TcpConn));
T2.Start();
}
catch (Exception e)
{
Program.LogEntry("Error", e.ToString(), "Fatal");
}
}
Methods:
public static void TcpConn()
{
try
{
Program.LogEntry("TCP Comm", "Theard start...");
Int32 port = Int32.Parse(ConfigurationManager.AppSettings["TCP_port"]);
IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["TCP_IP"]);
TcpServer = new TcpListener(localAddr, port);
TcpServer.Start();
const int bytesize = 2048 * 2048; // Constant, not going to change later
Byte[] bytes = new Byte[bytesize];
String data = null;
while (true)
{
TcpClient client = TcpServer.AcceptTcpClient();
IPAddress TcpIPClient = ((IPEndPoint)(client.Client.RemoteEndPoint)).Address;
NetworkStream stream = client.GetStream();
data = null;
Program.LogEntry("TCP Comm", "Connected! IP: " + TcpIPClient);
int i;
if (StopTcp == true)
{
Program.LogEntry("Service status", "Stoping TCP server...");
client.Close();
client.GetStream().Close();
TcpServer.Stop();
break;
}
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Program.LogEntry("TCP Comm", "Received: " + data);
string output = ProccessData(data);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(output);
Program.LogEntry("TCP Comm", "Output: " + output);
stream.Write(msg, 0, msg.Length);
}
stream.Close();
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e.ToString());
Program.LogEntry("TCP Comm", "SocketException: " + e.ToString(), "Fatal");
}
finally
{
Console.WriteLine("TCP: bye bye");
Program.LogEntry("TCP Comm", "Bye Bye", "Warning");
TcpServer.Stop();
System.Environment.Exit(6);
}
}
OPC
private static void DoOpc()
{
try
{
URL url = new URL(ConfigurationManager.AppSettings["OPC_Server"]);
OpcServer = new Opc.Da.Server(new OpcCom.Factory(), url);
OpcServer.Connect();
if (OpcServer.IsConnected == true)
{
Program.LogEntry("OPC Client", "Connected !");
}
else
{
Program.LogEntry("OPC Client", "NOT Connected!", "Fatal");
}
OpcServer.ServerShutdown += new Opc.ServerShutdownEventHandler(OnServerShutdown);
// Evidencia groupy/channelu ------Create group
Opc.Da.SubscriptionState state = new Opc.Da.SubscriptionState();
state.ClientHandle = 0;
//state.Name = "Device1";
state.UpdateRate = 500;
state.Active = true; // true;
Opc.Da.Subscription group = (Opc.Da.Subscription)OpcServer.CreateSubscription(state);
// Callback on Data change
group.DataChanged += new Opc.Da.DataChangedEventHandler(OnDataChange);
Opc.Da.Item NewItem;
List<Opc.Da.Item> NewItems = new List<Opc.Da.Item>();
foreach (var item in ActiveItems.Where(x => x.Active == true))
{
NewItem = new Opc.Da.Item();
NewItem.ClientHandle = 0;
NewItem.ItemName = item.Device + "." + item.Tag; //int4 = 32 bit
NewItems.Add(NewItem);
}
Item[] Items = NewItems.ToArray();
ItemResult[] ir = group.AddItems(Items);
SubscriptionState activatestate = group.GetState();
activatestate.Active = true;
group.ModifyState((int)Opc.Da.StateMask.Active, activatestate);
TcpConn();
}
catch (Exception e)
{
Program.LogEntry("Error with OPC connection", e.ToString(), "Fatal");
}
}

When I am multithreading I am only able to send message from the first thread once after that I am unable to send message from the first thread

I am working on a chat application which is multi-client in nature with a single server but I am facing an issue. When I connect a single client to the serve everything works perfectly but later when I connect 2 or more clients then I am only able to send one single messages from the first client and then the server stops receiving messages from the first client while I can still smoothly send messages from the second client without any issues
Below is my server code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpListener listener;
TcpClient client;
NetworkStream ns;
Thread t;
Thread main;
string[] client_name = new string[50];
int count;
int count1 = 0;
int indice = 0;
public Form1()
{
InitializeComponent();
button2.Enabled = false;
main = new Thread(runserver);
}
public void runserver()
{
listener = new TcpListener(IPAddress.Loopback, 8888);
listener.Start();
while (true)
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
//t = new Thread(connector);
var childSocketThread = new Thread(() =>
{
connector();
});
childSocketThread.Start();
//t.Start();
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
main.Start();
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
button3.Enabled = false;
String s = "Close";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
client.GetStream().Close();
client.Close();
listener.Stop();
button2.Enabled = false;
button1.Enabled = true;
textBox1.Text += "Server closed";
}
private void button3_Click(object sender, EventArgs e)
{
String s = textBox2.Text;
textBox1.Text += "Server >> " + textBox2.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
}
public void connector()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string statement = Encoding.ASCII.GetString(bytes, 0, bytesRead);
string temp = "";
if (statement[0] == '#')
{
count++;
while (statement[count] != '#')
{
temp += statement[count];
count++;
}
client_name[indice] = temp;
indice++;
statement = statement.Remove(0, temp.Length+2);
this.text1(statement);
count = 0;
}
else
this.text1(statement);
}
}
private void text1(string text)
{
int count2 = 1;
string str = "";
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(text1);
this.Invoke(d, new object[] { text });
}
else
{
if(text[0] == '*')
{
while (text[count2] != '*')
{
str += text[count2];
count2++;
}
text = text.Remove(0, str.Length + 2);
this.textBox1.Text += str + " >> " + text + "\r\n";
}
else
this.textBox1.Text += client_name[indice - 1] + " >> " + text + "\r\n";
}
}
And here is my client code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpClient client;
NetworkStream ns;
Thread t = null;
string client_name;
int port_num = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
client_name = textBox4.Text;
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
client = new TcpClient(textBox1.Text, port_num);
ns = client.GetStream();
String s = "#" + client_name + "#" +" Connected";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
t = new Thread(Connector);
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
String s = "*" + client_name + "*" + textBox3.Text;
textBox2.Text += client_name +" >> " + textBox3.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
}
public void Connector()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string data = Encoding.ASCII.GetString(bytes, 0, bytesRead);
if (data == "Close")
{
button3.Enabled = false;
t.Abort();
client.GetStream().Close();
client.Close();
}
else
this.Text1(data);
}
}
private void Text1(string text)
{
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(Text1);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox2.Text = this.textBox2.Text + "Server >> " + text + "\r\n";
}
}
private void button4_Click(object sender, EventArgs e)
{
string temp = textBox5.Text;
port_num = int.Parse(temp);
}
}
}
Kindly help me out with this also I am new with socket programming
TcpClient and NetworkStream in server code should be keeped in a list for futher use. Like blow server code
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpListener listener;
List<TcpClient> clients = new List<TcpClient>();
List<NetworkStream> ns = new List<NetworkStream>();
Thread t;
Thread main;
string[] client_name = new string[50];
int count;
int count1 = 0;
int indice = 0;
public Form1()
{
InitializeComponent();
button2.Enabled = false;
main = new Thread(runserver);
}
public void runserver()
{
listener = new TcpListener(IPAddress.Loopback, 8888);
listener.Start();
while (true)
{
TcpClient tmpClient = listener.AcceptTcpClient();
clients.Add(tmpClient);
ns.Add(tmpClient.GetStream());
//t = new Thread(connector);
var childSocketThread = new Thread(() =>
{
connector(ns.Count - 1);
});
childSocketThread.Start();
//t.Start();
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
main.Start();
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
button3.Enabled = false;
String s = "Close";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
for(int i = 0; i < ns.Count; i++)
{
ns[i].Write(byteTime, 0, byteTime.Length);
clients[i].GetStream().Close();
clients[i].Close();
}
listener.Stop();
button2.Enabled = false;
button1.Enabled = true;
textBox1.Text += "Server closed";
ns.Clear();
clients.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
String s = textBox2.Text;
textBox1.Text += "Server >> " + textBox2.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.ForEach(item => { item.Write(byteTime, 0, byteTime.Length); });
//ns.Write(byteTime, 0, byteTime.Length);
}
public void connector(int index)
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns[index].Read(bytes, 0, bytes.Length);
string statement = Encoding.ASCII.GetString(bytes, 0, bytesRead);
string temp = "";
if (statement[0] == '#')
{
count++;
while (statement[count] != '#')
{
temp += statement[count];
count++;
}
client_name[indice] = temp;
indice++;
statement = statement.Remove(0, temp.Length + 2);
this.text1(statement);
count = 0;
}
else
this.text1(statement);
}
}
private void text1(string text)
{
int count2 = 1;
string str = "";
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(text1);
this.Invoke(d, new object[] { text });
}
else
{
if (text[0] == '*')
{
while (text[count2] != '*')
{
str += text[count2];
count2++;
}
text = text.Remove(0, str.Length + 2);
this.textBox1.Text += str + " >> " + text + "\r\n";
}
else
this.textBox1.Text += client_name[indice - 1] + " >> " + text + "\r\n";
}
}
}

C#, WPF-application, many tcpclients connect a tcplistener(server)

TcpServer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Server
{
public class TcpServer
{
static ServerGUI serverGUI;
private const Int32 PORT = 13000;
private const String ADDRESS = "127.0.0.1";
private IPAddress localAddress;
public TcpListener tcpServer;
private static Byte[] bytes;
private static String data;
static DateTime localDate;
static String cultureName = "de-DE";
static CultureInfo cultureInfo;
private static int clientCount = 0;
private const char SEPERATOR = '|';
static NetworkStream stream;
public TcpServer()
{
serverGUI = new ServerGUI();
serverGUI.Show();
cultureInfo = new CultureInfo(cultureName);
BackgroundWorker worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(Worker1_DoWork);
worker1.RunWorkerAsync();
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
localAddress = IPAddress.Parse(ADDRESS);
tcpServer = new TcpListener(localAddress, PORT);
localDate = DateTime.Now;
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") chatserver has started.\n");
tcpServer.Start();
while (true)
{
TcpClient client = await tcpServer.AcceptTcpClientAsync();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
}));
}
catch (SocketException socketEx)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(socketEx.Message + "\n");
}));
}
catch (Exception ex)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(ex.Message + "\n");
}));
}
finally
{
if (tcpServer != null)
{
tcpServer.Stop();
}
}
}
private static async void ThreadProc(object obj)
{
await serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(async delegate ()
{
var client = (TcpClient)obj;
bytes = new Byte[256];
data = null;
// Get a stream object for reading and writing
stream = client.GetStream();
int i = 0;
while (true)
{
if (stream.CanRead)
{
i = await stream.ReadAsync(bytes, 0, bytes.Length);
}
localDate = DateTime.Now;
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] receivedStr = data.Split(SEPERATOR);
byte[] msg = null;
if (receivedStr != null && receivedStr[0] == "new")
{
clientCount++;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Welcome, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") new client recognized!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
}
else if (receivedStr != null && receivedStr[0] == "close")
{
clientCount--;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Goodbye, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") client disconnected!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
client.Close();
break;
}
else
{
msg = System.Text.Encoding.ASCII.GetBytes(data);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
}
}));
}
}
}
(Client)MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Client
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Int32 port = 13000;
private String hostname = "127.0.0.1";
public TcpClient tcpClient;
DateTime localDate;
String cultureName = "de-DE";
CultureInfo cultureInfo;
BackgroundWorker worker1;
NetworkStream stream;
bool work = false;
private const char SEPERATOR = '|';
public MainWindow()
{
InitializeComponent();
buttonDisconnect.IsEnabled = false;
textBoxServerIP.Text = "127.0.0.1:13000";
textBoxNickname.Text = "User";
cultureInfo = new CultureInfo(cultureName);
worker1 = new BackgroundWorker();
worker1.DoWork += Worker1_DoWork;
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
try
{
while (work)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hallo");
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = 0;
if (stream.CanRead)
{
bytes = await stream.ReadAsync(data, 0, data.Length);
}
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
string[] receivedStr = responseData.Split(SEPERATOR);
if (receivedStr != null && receivedStr[0] == "chatserver")
{
textBoxChatRoom.Text += receivedStr[0] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[1] + "\n\n";
}
else if (receivedStr != null && receivedStr[0] == "msg")
{
textBoxChatRoom.Text += receivedStr[1] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[2] + "\n";
}
else
{
textBoxChatRoom.Text += responseData + "\n\n";
}
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}));
}
private async void buttonConnect_Click(object sender, RoutedEventArgs e)
{
string[] connectionStr = { "" };
if (!textBoxServerIP.Text.Equals(null) && textBoxServerIP.Text != "")
{
connectionStr = textBoxServerIP.Text.Split(':');
try
{
hostname = connectionStr[0];
port = Int32.Parse(connectionStr[1]);
tcpClient = new TcpClient(connectionStr[0], Int32.Parse(connectionStr[1]));
//localDate = DateTime.Now;
textBoxChatRoom.Text += "Connecting to server " + connectionStr[0] + "...\n";
if (tcpClient.Connected)
{
textBoxChatRoom.Text += "Connected!\n";
textBoxServerIP.IsEnabled = false;
textBoxNickname.IsEnabled = false;
buttonConnect.IsEnabled = false;
buttonDisconnect.IsEnabled = true;
localDate = DateTime.Now;
stream = tcpClient.GetStream();
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("new" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
work = true;
worker1.RunWorkerAsync();
}
else
{
textBoxChatRoom.Text += "not connected!\n";
}
}
catch (ArgumentNullException argumentNullExceptionEx)
{
textBoxChatRoom.Text += argumentNullExceptionEx.Message + "\n";
}
catch (ArgumentOutOfRangeException argumentOutOfRangeEx)
{
textBoxChatRoom.Text += argumentOutOfRangeEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (FormatException formatEx)
{
textBoxChatRoom.Text += formatEx.Message + "\n";
}
catch (OverflowException overflowEx)
{
textBoxChatRoom.Text += overflowEx.Message + "\n";
}
catch (CultureNotFoundException cultureNotFoundEx)
{
textBoxChatRoom.Text += cultureNotFoundEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
else
{
textBoxChatRoom.Text += "Please enter serverip!\n";
}
}
private async void buttonDisconnect_Click(object sender, RoutedEventArgs e)
{
work = false;
buttonConnect.IsEnabled = true;
textBoxServerIP.IsEnabled = true;
textBoxNickname.IsEnabled = true;
buttonDisconnect.IsEnabled = false;
byte[] msg = System.Text.Encoding.ASCII.GetBytes("close" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
private void buttonExit_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private async void buttonSend_Click(object sender, RoutedEventArgs e)
{
try
{
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("msg" + SEPERATOR + textBoxNickname.Text.ToString() + SEPERATOR + textBoxSend.Text);
stream = tcpClient.GetStream();
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
}
}
The connection between server and clients functions but if I send something into the networkstream with one client, the other clients don't receive anything. This should be a little chatroom-WPF-application
I have a problem, that i couldn't receive and send between multiple clients and I don't know what I am doing wrong...
Please can somebody help...

send message from my web page (client) to a pc (server)?

i would like to send message from my web page (client) to a pc
Problem comes in when I try to send data. It complains about this line: m_socWorker.Send(byData); Error Message is Object reference not set to an instance of an object.
here is my code
// Counts the pings
private int pingsSent;
// Can be used to notify when the operation completes
AutoResetEvent resetEvent = new AutoResetEvent(false);
public static Socket m_socWorker;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList2.SelectedIndex != null)
{
// Reset the number of pings
pingsSent = 0;
// Clear the textbox of any previous content
TextBox2.Dispose();
TextBox2.Text += "Pinging " + DropDownList1.SelectedValue + " with 32 bytes of data:\r\n\r\n";
// Send the ping
Thread thd = new Thread(new ThreadStart(SendPing));
thd.Start();
//SendPing();
try
{
UdpClient udpclient = new UdpClient();
IPAddress remotipadd = IPAddress.Parse(DropDownList1.SelectedValue);
udpclient.Connect(remotipadd,10001);
byte[] data = new byte[1024];
IPEndPoint senderip = new IPEndPoint(remotipadd, Convert.ToInt32(DropDownList2.SelectedValue));
udpclient.Connect(senderip);
TextBox2.Text += "Connect";
// listbox1.Items.Add("connected");
}
catch (SocketException s)
{
MessageBox.Show(s.Message);
}
}
}
private void SendPing()
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
// Create an event handler for ping complete
pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);
// Create a buffer of 32 bytes of data to be transmitted.
byte[] packetData = Encoding.ASCII.GetBytes("................................");
// Jump though 50 routing nodes tops, and don't fragment the packet
PingOptions packetOptions = new PingOptions(50, true);
// Send the ping asynchronously
pingSender.SendAsync(DropDownList1.SelectedValue, 5000, packetData, packetOptions, resetEvent);
}
private void pingSender_Complete(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
TextBox2.Text += "Ping was canceled...\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else if (e.Error != null)
{
TextBox2.Text += "An error occured: " + e.Error + "\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply pingResponse = e.Reply;
// Call the method that displays the ping results, and pass the information with it
ShowPingResults(pingResponse);
}
}
public void ShowPingResults(PingReply pingResponse)
{
if (pingResponse == null)
{
// We got no response
TextBox2.Text += "There was no response.\r\n\r\n";
return;
}
else if (pingResponse.Status == IPStatus.Success)
{
// We got a response, let's see the statistics
TextBox2.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n";
}
else
{
// The packet didn't get back as expected, explain why
TextBox2.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n";
}
// Increase the counter so that we can keep track of the pings sent
pingsSent++;
// Send 4 pings
if (pingsSent < 4)
{
SendPing();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
Object objData = TextBox2.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
//Session["m_socWorker"] = m_socWorker;
//m_socWorker = (Socket) Session["m_socWorker"];
m_socWorker.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

Why doesn't my disconnect button work?

I am working on this GUI for serial port application. I recently added stop and wait protocols to the application. Surprisingly my disconnect button stopped working. I have thought through the logic and I have not been able to find the problem.
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public bool packetreceived = false;
private SerialPort sp = null; //<---- serial port at form level
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//delegate variable to disconnect
public AddDataDelegate disconnectDelegate = null;
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
}
/**
* Takes byte array and returns a string representation
*
*/
public String parseUARTData(byte[] data)
{
if (data.Length == 11)
{
String rv = "";
DataFields d = new DataFields();
if (!packetreceived)
{
d = mainLogic.parseData(data);
packetreceived = true;
}
//TODO
System.Threading.Thread.Sleep(5000);
if (d.sequence == 0)
{
sp.Write("1\r\n");
}
else
{
sp.Write("0\r\n");
}
packetreceived = false;
//now display it as a string
rv += STR_OPCODE + " = " + d.opcode + "\n";
rv += STR_CRC + " = " + d.crc + "\n";
rv += STR_SEQ + " = " + d.sequence + "\n";
rv += STR_FLAGS + " = " + d.flags + "\n";
rv += STR_TEMP + " = " + d.temperature + "\n";
rv += STR_HUMID + " = " + d.humidity + "\n";
rv += STR_PH + " = " + d.ph + "\n";
return rv + "\n\n";
}
else
{
return Encoding.ASCII.GetString(data);
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s = sp.ReadExisting();
if (disconnectDelegate != null)
{
disconnectDelegate.Invoke(s);
}
richTextBox1.Invoke(this.myDelegate, new Object[] { parseUARTData(Encoding.ASCII.GetBytes(s)) });
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
//sp.PortName = this.comboBox1.SelectedItem.ToString();
sp.Open();
}
// send data to port
sp.Write("####,###########\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (sp.IsOpen)
{
// send data to port
sp.Write("+++\r\n");
//add the delegate
disconnectDelegate = new AddDataDelegate(onDisconnect);
//sp.WriteTimeout = 500;
// sp.Write("####,0\r\n");
}
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (string port in ports)
//{
// comboBoxSerialPorts.Items.Add(port);
//}
}
private void onDisconnect(string msg)
{
string trimmedMsg = msg.Trim();
if (trimmedMsg.Equals("OK"))
{
//send the second time
sp.Write("##,0\r\n");
//null the object
disconnectDelegate = null;
}
}
private void comPort_Click(object sender, EventArgs e)
{
try
{
if (sp.IsOpen)
{
//send data to port
sp.Write("1\r\n");
MessageBox.Show("bluetooth is transmitting data...");
//message box telling user that you are asking for data.
}
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}

Categories

Resources