New to WinForms but not ASP.NET or C#. Trying to make client/server app. Successfully received data from client on server but having troubles displaying it on server program winform. Codes are:
Server App code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
TcpListenerEx listener = new TcpListenerEx(ep); //set host to listen
if (!listener.Active)
{
listener.Start();
}
while (true)
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
var s = listener.AcceptTcpClient();
s.GetStream().Read(message, 0, byteSize); //obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
addMessage(g);
}
}
private void addMessage(string m)
{
this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Client App code:
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClientApp
{
public partial class ClientApp : Form
{
public ClientApp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text);
using (var client = new TcpClient("127.0.0.1", 1234))//make connection with the host
{
NetworkStream stream = client.GetStream();/*obtain network stream*/
stream.Write(message, 0, message.Length);
}
}
private void textBox1_Click(object sender, EventArgs e)
{
txtFromClient.Text = "";
}
}
}
Everything is happening as planned except for displaying received data on server program's Form1's textbox. On debugging, I confirmed the correct value received in variable m of line this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;. Only problem is that this value cannot be displayed and hence seen on the Form1 of server program.
With the help and guidance from #AdrianoRepetti, solution to the given problem was furnished through the following code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Linq;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess.
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
IPEndPoint ep = e.Argument as IPEndPoint;
TcpListenerEx listener = new TcpListenerEx(ep);
if (!listener.Active)
{
listener.Start();
}
while (true)
{
try
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
using (var s = listener.AcceptTcpClient())
{
s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
backgroundWorker1.ReportProgress(0, g);
}
}
catch (Exception ex)
{
backgroundWorker1.ReportProgress(0, ex.Message);
}
finally
{
listener.Stop();
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
textBox1.AppendText(Environment.NewLine + ">> " + e.UserState);
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Hope it helps.
Related
This is a TCP Program which receives data from a TCP connection, then parse it and transfer it to another TCP connection. When I exit application, it doesn't work. It will remain as a process in the system.
As I am not a very experienced developer, can someone please help me to find the error in this code..
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.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Machine_Feeder
{
public partial class FeederControlMonitor : Form
{
TcpListener Listener = null;
public string Status = string.Empty;
public Thread T = null;
public FeederControlMonitor()
{
InitializeComponent();
}
private void FeederControlMonitor_Load(object sender, EventArgs e)
{
txtStatus.Text = "Feeder waiting for data...";
ThreadStart Ts = new ThreadStart(StartReceiving);
T = new Thread(Ts);
T.Start();
}
public void StartReceiving()
{
ReceiveTCP(9100);
}
public void ReceiveTCP(int portN)
{
try
{
Listener = new TcpListener(IPAddress.Any, portN);
Listener.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
Console.WriteLine(ex.Message);
}
try
{
while (true)
{
Socket client = Listener.AcceptSocket();
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data);
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.Start();
}
Listener.Stop();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
}
}
public void ParseData(string data)
{
var useFulData = data.Substring(data.IndexOf("F1")).Replace(" ", " ");// Space
useFulData = useFulData.Remove(useFulData.IndexOf("<ETX>"));
string[] delimeters = { "<DEL>", "<ESC>" };
var listOfValues = useFulData.Split(delimeters, StringSplitOptions.None).ToList();
int pos = 0;
for (int i = 1; i < listOfValues.Count; i += 2, pos++)
{
listOfValues[pos] = listOfValues[i];
}
listOfValues.RemoveRange(pos, listOfValues.Count - pos);
txtHealthCard.Invoke((Action)delegate { txtHealthCard.Text = listOfValues[0]; });
txtCID.Invoke((Action)delegate { txtCID.Text = listOfValues[1]; });
txtMedicalFitLocation.Invoke((Action)delegate { txtMedicalFitLocation.Text = listOfValues[2]; });
txtGender.Invoke((Action)delegate { txtGender.Text = listOfValues[3]; });
txtAge.Invoke((Action)delegate { txtAge.Text = listOfValues[4]; });
txtPatientName.Invoke((Action)delegate { txtPatientName.Text = listOfValues[5]; });
MyProtocolMaker(listOfValues[5],
listOfValues[4],
listOfValues[2],
listOfValues[3],
listOfValues[8],
listOfValues[1],
listOfValues[10],
);
}
private void btnExit_Click(object sender, EventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
private void MyProtocolMaker(
string patientName,
string patientAge,
string mfitLocation,
string gender,
string healthCardNo,
)
{
string feederInfo = "^^^P^PI" + healthCardNo + "^PN" + patientName + "^PA" + patientAge + "^PS" + gender + "^P7" + mfitLocation +"^_SS^^^_S";
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient("127.0.0.1", 8001);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(feederInfo);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
serverStream.Close();
clientSocket.Close();
}
private void FeederControlMonitor_FormClosing(object sender, FormClosingEventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
}
}
You problem is, that you are creating threads within the thread. These threads are keeping the application alive. Try marking them as background threads: (This is red-tape solution)
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data); // <-- the thread hangs on these and will block termination
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.IsBackground = true; // <---
childSocketThread.Start();
When thread are not marked as background (default), they will block application termination. You should create a list to store the client threads, so you can exit those threads nicely.
You should never abort a thread, unless there is no other way. Instead of aborting, you should exit the while loop in the thread.
As nice way is using a ManualResetEvent:
fields:
private ManualResetEvent _terminating = new ManualResetEvent(false);
in thread:
while (_terminating.WaitOne(0))
{
// thread code
}
on exit:
_terminating.Set();
T.Join();
Sidenote: TCP is streaming, so just reading 10k of bytes ones, does not guarantee a complete packet.
I have tried 2 of how to make multi client, which is multi thread and asynchronous server. Both didn't work for me. The multi thread can make client send broadcast to all client, but some of them didn't receive the broadcasted data. While the asynchronous server cannot make the client connect too long. I don't know whether it's my code that's wrong or what. Please help me based on my latest working 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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public String text_to_send;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //Using the PC's IP
foreach (IPAddress address in localIP) {
if (address.AddressFamily == AddressFamily.InterNetwork) {
textBox5.Text = address.ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Button to start the server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox6.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //Receiving data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("You : " + receive + "\n Received : " + receive.Length.ToString() + " byte. \n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //Sending data
{
if (client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me : " + text_to_send + "\n Sent : " + text_to_send.Length.ToString() + " byte \n"); }));//Text that will appeared on the screen after we enter the text that we type
}
else
{
MessageBox.Show("Send Failed!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connected as client
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox3.Text), int.Parse(textBox4.Text));
try
{
client.Connect(IP_End);
if (client.Connected) {
textBox2.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if (textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
N.B : Just translated the comment into English
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
In the below code, I am getting null reference exception I didn't understand why I am getting that. Please help me to solve it.
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.Data.SqlClient;
using System.Configuration;
namespace TCPListener
{
public partial class Form1 : Form
{
// Declare our worker thread
private Thread workerThread = null;
public Form1()
{
InitializeComponent();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
public void timer1_Tick(object sender, EventArgs e)
{
}
public TcpListener server = null;
public Int32 port = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO"].ToString());
public IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["IP"].ToString());
public void OpenSocket()
{
try
{
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
}
catch (SocketException e)
{
Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message);
}
finally
{
Common.CommonControls.writeToLogFile("INICIO DE ESCUCHA EN " + DateTime.Now);
}
}
private void ReceiveTcpData()
{
//Instancio los objetos
Entities.Program oPosiciones = new Entities.Program();
DataAccess.Program oPosicionesDA = new DataAccess.Program();
try
{
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
//TcpClient client = server.AcceptTcpClient();
TcpClient cliente = new TcpClient();
try
{
cliente = server.AcceptTcpClient();
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
data = null;
// Get a stream object for reading and writing
NetworkStream stream = cliente.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// Process the data sent by the client.
data = data.ToUpper();
if (data.Substring(0, 2) == "##")
{
//SalidaMonitor("Paquete recibido: LOGON REQUEST del equipo");
cliente.Close();
this.workerThread.Interrupt();
return;
}
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//Show data on monitor
SalidaMonitor("Paquete recibido " + DateTime.Now + ": " + data);
//Declare entities
oPosiciones.Paquete = data;
//Database action
oPosicionesDA.InsertarPosiciones(oPosiciones);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//SalidaMonitor("Paquete enviado: " + msg);
}
// Shutdown and end connection
cliente.Close();
}
catch (SocketException e)
{
Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message);
}
catch (SqlException x)
{
Common.CommonControls.writeToLogFile("SQL ERROR: " + x.Message);
}
catch (Exception y)
{
Common.CommonControls.writeToLogFile("ERROR: " + y.Message);
}
finally
{
oPosiciones = null;
oPosicionesDA = null;
this.workerThread.Interrupt();
}
}
private void SalidaMonitor(string data)
{
lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.Items.Add(data.ToString()); }));
lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.SelectedIndex = lstMensajes.Items.Count - 1; lstMensajes.SelectedIndex = -1; }));
}
private void Form1_Load(object sender, EventArgs e)
{
OpenSocket();
}
private void Form1_Close(object sender, FormClosingEventArgs e)
{
server.Stop();
}
}
}
In the above code, I am getting error at cliente = server.AcceptTcpClient();. I don't understand why it's happening. If you need any information, let me know. Thanks
The Problem
in the constructor of the form you are creating and starting new Thread.
and this thread will call the ReceiveTcpData method, which user the server variable (and at this point this variable was not initialized yet) WHY??
because the server variable is initialized in the Form_Load which call the OpenSocket method to initalize the server variable. The most important part is The Form_Load method is called AFTER the constructor of the form.
In other words, the Thread is using the server variable before you initialize it.
The Solution
use the following constructor, and remove the Form_Load event handler
public Form1()
{
InitializeComponent();
// add this line.
OpenSocket();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
Update
For the person who prefer to do everything in the Form_Load
here is another solution
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// add this line.
OpenSocket();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
Well, if it is in that line, it is because server is not initialized.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys I am new at the subject of Sockets
and I really need you help.
I am doing system of server and clients (like chat)
but something diffrent, I am doing it with Windows Form Application
in my server : I have list of sockets of all pepole that connect to the server, that already get acception from the server.
And I wanna to do a Timer that every X seconds it will runs on my List and check if the person is still connection I mean in that , that the person still connect on the internet and still can get packages and if not to remove him from the list.
someone can help me in c# how do it??
now at the server if someone is Exit the program Or if the internet is logout how i can check if the Client is out
and if yes so Close his connection?
i Read about TimeOut but how use it??? if it usfull?
Server:
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
{
Socket sck;
static List<Socket> acc;
static List<Thread> thr;
//List<UserAt> thr;
static int port = 9000;
static IPAddress ip;
static Thread NewCon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
acc = new List<Socket>();
//thr = new List<UserAt>();
thr = new List<Thread>();
NewCon = new Thread(getNewConnection);
//Console.WriteLine("please enter your host port ");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
ip = IPAddress.Parse("127.0.0.1");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(ip, port));
sck.Listen(0);
NewCon.Start();
}
/// <summary>
/// get new connection from client
/// </summary>
public void getNewConnection()
{
while (true)
{
acc.Add(sck.Accept());
var t = new Thread(() => ReciveMessage(acc.Count-1));
t.Start();
thr.Add(t);
/* UserAt a = new UserAt();
a.index = acc.Count - 1;
a.thread = new Thread(() => ReciveMessage(a.index));
a.thread.Start();
thr.Add(a);
* */
}
}
public void ReciveMessage(int index)
{
while (true)
{
try
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = acc[index].Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
//MessageBox.Show(Encoding.Default.GetString(Buffer));
//listBox1.Items.Add(Encoding.Default.GetString(Buffer));
SetText(Encoding.Default.GetString(Buffer));
}
catch
{
// thr[index].thread.Abort();
/*thr.RemoveAt(index);
for (int i = index+1; i < thr.Count;i++ )
{
thr[i].index -= 1;
}*/
break;
}
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
public string getIp()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
}
}
Client
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 Client
{
public partial class Form1 : Form
{
static string name = "";
static int port = 9000;
static IPAddress ip;
static Socket sck;
public Form1()
{
InitializeComponent();
}
public void ReciveMessage()
{
while (true)
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
SetText(Encoding.Default.GetString(Buffer));
//MyChat.Items.Add(Encoding.Default.GetString(Buffer));
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.MyChat.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.MyChat.Items.Add(text);
}
}
private void Login_Click(object sender, EventArgs e)
{
name = UserName.Text;
ip = IPAddress.Parse("127.0.0.1");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Connect(new IPEndPoint(ip, port));
ReciveMes.Enabled = true;
byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + " connected");
sck.Send(conmsg, 0, conmsg.Length, 0);
SendToServer.Enabled = true;
}
catch
{
MessageBox.Show("חיבור נכשל");
}
}
private void SendToServer_Click(object sender, EventArgs e)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + MyMessage.Text);
sck.Send(sdata, sdata.Length, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(SendToServer.Enabled)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + "Is Quit");
sck.Send(sdata, sdata.Length, 0);
}
}
}
}
i have error shown:
'Timer' is an ambiguous reference between 'System.Windows.Forms.Timer' and 'System.Threading.Timer'
when i added the code for clock
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.Sockets;
using System.Threading;
using System.Security.Cryptography;
namespace SocketClient
{
public partial class SocketClient : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public SocketClient()
{
InitializeComponent();
Timer timer = new Timer();
timer.Tick += new EventHandler(TimerOnTick);
timer.Interval = 1000;
timer.Start();
}
private void TimerOnTick(object sender, EventArgs ea)
{
Invalidate();
}
protected override void OnPaint(PaintEventArgs pea)
{
StringFormat strfmt = new StringFormat();
strfmt.Alignment = StringAlignment.Far;
strfmt.LineAlignment = StringAlignment.Far;
pea.Graphics.DrawString(DateTime.Now.ToString("F"),
Font, new SolidBrush(ForeColor),
ClientRectangle, strfmt);
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textDisplay.Text = textDisplay.Text + Environment.NewLine + " >> " + readData;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
// show the message if no input is enter.
if (string.IsNullOrEmpty(textName.Text) || string.IsNullOrEmpty(textPort.Text) || string.IsNullOrEmpty(textIP.Text))
{
MessageBox.Show("Please enter Name, IP Address & Port #");
}
else
{
//connect to the server if all 3 input is enter
readData = "Conected to NYP Server ...";
msg();
clientSocket.Connect(textIP.Text, Convert.ToInt32(textPort.Text));
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textName.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
// Show msg box if no server is connected
if (serverStream == null)
{
MessageBox.Show("Please connect to a server first!");
return;
}
// Send text
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
// Clear text
textSend.Text = "";
}
private void textDisplay_TextChanged(object sender, EventArgs e)
{
textDisplay.SelectionStart = textDisplay.Text.Length;
textDisplay.ScrollToCaret();
textDisplay.Refresh();
}
private void textSend_TextChanged(object sender, EventArgs e)
{
buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
}
}
}
There are various options here:
Use an alias:
using UITimer = System.Windows.Forms.Timer;
...
UITimer timer = new UITimer();
Use the fully qualified name:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
Use a namespace alias:
using WinForms = System.Windows.Forms;
...
WinForms::Timer timer = new WinForms::Timer();
However, I would personally suggest splitting up the user interface code from the network code - at which point it's unlikely to be an issue.
I would also note that you're currently reading from the stream without taking the return value into account - that's a bad idea, as you don't know how much of the buffer actually contains new data.
The problem is that you are
using System.Windows.Forms;
using System.Threading;
Both of these namespaces have a Timer class and the compiler can't tell which one to use. When you declare your Timer, use the full name, either:
System.Windows.Forms.Timer
or
System.Threading.Timer
WinForms Timer Class
Threading Timer Class
Based on your usage of the class, I think you want System.Windows.Forms.Timer, like so:
public SocketClient()
{
InitializeComponent();
var timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(TimerOnTick);
timer.Interval = 1000;
timer.Start();
}