This is my form
https://i.stack.imgur.com/M7fuy.png
This is my 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.Sockets;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new
System.Net.Sockets.TcpClient();
//NetworkStream serverStream = default(NetworkStream);
//string readData = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("192.168.0.167", 5000);
label1.Text = "Client Socket Program - Server Connected ...";
}
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg(returndata);
textBox2.Text = "";
textBox2.Focus();
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
}
when I click the start button in the code i am getting this error to connect to the server. please guide me how to get rid of this error and connect to the server instead.
https://i.stack.imgur.com/wDSCI.png
Related
I am trying to set up two programs in C#. Basically, a simple server side set up where I want the client to listen for an image from the Server. Then, upon receiving the image, will display it in a PictureBox.
**I keep running into the following error:
A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll or Parameter is not Valid**
SERVER SIDE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 ServerComputer
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
Socket sendsocket;
private void goLive_Click(object sender, EventArgs e)
{
try
{
sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//The instantiation of socket, IP for 192.168.1.106, 10001 for Port
IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse(ipAddress.Text.Trim()), 10001);
sendsocket.Connect(ipendpiont);
//Establishment of end point
Thread th = new Thread(new ThreadStart(threadimage));
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
this.Hide(); //Hidden form
}
private Bitmap GetScreen()
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
return bitmap;
}
private void threadimage()
{
try
{
while (true)
{
MemoryStream ms = new MemoryStream();
GetScreen().Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); //Here I use the BMP format
byte[] b = ms.ToArray();
sendsocket.Send(b);
Thread.Sleep(67); //I'm here to set to send a second
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return;
}
}
}
}
CLIENT SIDE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClientComputer
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
Socket hostSocket;
Thread thread;
string localIP = string.Empty;
string computrHostName = string.Empty;
private void mainForm_Load(object sender, EventArgs e)
{
computrHostName = Dns.GetHostName();
IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in hostname.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
}
private void liveScreen_Click(object sender, EventArgs e)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(localIP), 10001);
//Connection node
receiveSocket.Bind(hostIpEndPoint);
receiveSocket.Listen(10);
MessageBox.Show("start");
hostSocket = receiveSocket.Accept();
thread = new Thread(trreadimage);
thread.Start();
thread.IsBackground = true;
}
private void trreadimage()
{
int dataSize, i = 0;
try
{
while (true)
{
i++;
byte[] b = new byte[1024 * 1024 * 20]; //Picture of great
dataSize = hostSocket.Receive(b,0,b.Length,SocketFlags.None);
MemoryStream ms = new MemoryStream(b,0,dataSize,true);
//bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = Image.FromStream(ms);
img.Save("Image"+i+".Jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
videoBox.Image = img;
Console.WriteLine("Image Size: " + dataSize);
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
thread.Abort();
}
}
}
}
I can't stop repeating: never ever send raw data to a socket and expect to receive them the same way on another end. Use a protocol instead, to describe your network activity. In simplest case, send DWORD first that designated total length of your image. Same time, it's worth to reuse existing protocols like HTTP or what can fit your needs.
Why to bother? Well, if your "network" is just a piece of wire with two jacks on ends that placed directly into network cards of your PCs, that maybe happen to work OK (and still no 100% warranty). In real case, your "network connection" is a pack of inter-connections between routers, firewalls, switches and all that sort of hidden machinery in-between. They can (and will!) re-shape your stream the way they find useful for them. So, on the other end, how can your counterparty understand: is there everything received? how many packets to expect? etc. etc. etc.
So, sending some business data directly to socket is the same efficient as yelling to the window if you plan to say something to your friend living nearby. And, usually we use a phone with that kind of communication protocol "hey, Peter?.. yes, it's me.. listen, take care about your car as hail shower is coming... Bye!". See the difference?
Following code is working now, and I have few suggestions,
Try Async methods/events to receive and send data through socket instead of using loop or recursive methods.
Server Code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ServerComputer
{
publicpartialclassmainForm : Form
{
public mainForm()
{
InitializeComponent();
}
Socket sendsocket;
privatevoid goLive_Click(object sender, EventArgs e)
{
try
{
sendsocket = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//The instantiation of socket, IP for 192.168.1.106, 10001 for PortIPEndPoint ipendpiont = newIPEndPoint(IPAddress.Parse(ipAddress.Text.Trim()), 10001);
sendsocket.Connect(ipendpiont);
//Establishment of end pointThread th = newThread(newThreadStart(threadimage));
th.IsBackground = true;
th.Start();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return;
}
this.Hide(); //Hidden form
}
privateBitmap GetScreen()
{
Bitmap bitmap = newBitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
return bitmap;
}
privatevoid threadimage()
{
try
{
MemoryStream ms = newMemoryStream();
GetScreen().Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); //Here I use the BMP formatbyte[] b = ms.ToArray();
sendsocket.Send(b);
ms.Close();
}
catch (Exception ee)
{
// MessageBox.Show(ee.Message);//return;
}
Thread.Sleep(1000);
threadimage();
}
}
}
Clint Code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 ClientComputer
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
Socket hostSocket;
Thread thread;
string localIP = string.Empty;
string computrHostName = string.Empty;
private void mainForm_Load(object sender, EventArgs e)
{
computrHostName = Dns.GetHostName();
IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in hostname.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
this.Text = this.Text + " | " + localIP;
}
private void liveScreen_Click(object sender, EventArgs e)
{
connectSocket();
}
private void connectSocket()
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(localIP), 10001);
//Connection node
receiveSocket.Bind(hostIpEndPoint);
receiveSocket.Listen(10);
MessageBox.Show("start");
hostSocket = receiveSocket.Accept();
thread = new Thread(new ThreadStart(trreadimage));
thread.IsBackground = true;
thread.Start();
}
private void trreadimage()
{
int dataSize;
string imageName = "Image-" + System.DateTime.Now.Ticks + ".JPG";
try
{
dataSize = 0;
byte[] b = new byte[1024 * 10000]; //Picture of great
dataSize = hostSocket.Receive(b);
if (dataSize > 0)
{
MemoryStream ms = new MemoryStream(b);
Image img = Image.FromStream(ms);
img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
videoBox.Image = img;
ms.Close();
}
}
catch (Exception ee)
{
//MessageBox.Show(ee.Message);
//thread.Abort();
}
System.Threading.Thread.Sleep(1500);
trreadimage();
}
}
}
MemoryStream ms = new MemoryStream(b);
Image img = Image.FromStream(ms);
img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
videoBox.Image = img;
The error may due to corrupted or incomplete bmp image received in the MemoryStream it worked fine for me after increasing the socket send/receive buffers values
so adjust the sender "Socket.SendBufferSize" and the receiver "Socket.ReceiveBufferSize" to large values for example SendBufferSize = 1024 * 1024 * 20
this will help sending the entire image at once.
or another solution is to check whether the received data size (b.length) is the same as the sent image data size, before the code line of forming the received image stream
So I am making an online chat room in C#, and I am getting this error on line 71.
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values.'
I have both a client program and a server program. Here is the code to the client program. The line that is giving me the error is in asterisks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace ChatProgram
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new
System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
static int maxUsage = 0;
string noName = "Anonymous";
int tick = 0;
public Form1()
{
InitializeComponent();
}
private void enterButton_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(readRichTxt.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
readData = "Connected to server...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
string nameTxt = nameTextBox.Text;
if (nameTxt == String.Empty)
{
nameTxt = noName;
tick = 1;
}
else
{
tick = 0;
}
readRichTxt.SelectionColor = Color.Red;
readRichTxt.AppendText("\n" + nameTxt + " has joined." + "\n");
++maxUsage;
sendButton.Enabled = true;
if (maxUsage == 3)
{
enterButton.Enabled = false;
}
}
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
readRichTxt.Text = readRichTxt.Text + Environment.NewLine + " >> " + readData;
}
private void sendButton_Click(object sender, EventArgs e)
{
string nameTxt = nameTextBox.Text;
string userTyped = userTypeBox.Text;
if (userTyped == String.Empty)
{
return;
}
if (tick == 1)
{
readRichTxt.AppendText(noName + ": " + userTyped);
}
else
{
readRichTxt.AppendText(nameTxt + ": " + userTyped);
}
userTypeBox.Clear();
}
}
}
Please help, I am completely stumped at this point.
what is the size of:
buffSize = clientSocket.ReceiveBufferSize;
?
this is likely larger than what you declared here:
byte[] inStream = new byte[10025];
and thus the error is roughly telling you:
buffSize > inStream.Length
which results in the out of bounds like error.
I Tried to use sockets in asp.net using C#.
The commented line in the client code gives me error.
The server code is running properly.
This is the Client Code which Gives error.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Post_Click(object sender, EventArgs e)
{
if (txtmsg.Text != "")
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtmsg.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
// This line gives error Saying Object reference not set to an instance of an object.
serverStream.Flush();
}
}
protected void Connect_Click(object sender, EventArgs e)
{
if (txtSub.Text != "")
{
try
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtSub.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
catch
{
//Disconnect();
}
}
}
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
txtget.Text = txtget.Text + Environment.NewLine + " >> " + readData;
}
}
Your serverSteam object isn't being properly initialised and therefore causes an object error when you try to reference it.
You need to create a new NetworkSteam with a Socket object, and ensure that your Socket object is connected:
Socket my_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
..
// connect socket and any other operations
..
NetworkStream my_network_stream = new NetworkStream(my_socket);
I would like to encrypt my message when sending to the server from client, how can I do it?
Client
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;
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();
}
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)
{
readData = "Connected to NYP Chat Server ...";
msg();
//clientSocket.Connect("127.0.0.1", 8888);
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);
}
}
}
server
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
//TcpListener serverSocket = new TcpListener(portFromAppConfig);
TcpListener serverSocket = new TcpListener(9999);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Welcome to NYP Chat Server ");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Connected ", dataFromClient, false);
Console.WriteLine(dataFromClient + " has join the chat room ");
handleClient client = new handleClient();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClient
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClient
}//end namespace
Absolute simplest way is to rip all the code you wrote and just use WCF.
Next simplest way is to use a secure stream instead of the raw Network Stream, like SslStream or NegotiateStream. There a full blown sample at Secure Streams Sample that shows both the client and the server for NTLM/Kerberos and SChannel protocols (aka SSL/TLS).
One thing you should absolutely not do is write your own encryption. Encrypting messages is trivial and you'll find a myriad samples on the web. But creating a key exchange protocol so you actually have something to encrypt with is one of the hardest tasks in crypto. Use one of the industry acknowledged key exchange schemes like Kerberos or SSL/TLS, and these are already implemented in the two stream classes I linked.
C# provides a namespace for cryptography System.Security.Cryptography... for start you could check that out... Or try to implement a cryptography algorithm like Vernamm which is the simplest and easiest to implement. Or if you want to be fully secured you should use both the System.Security.Cryptography namespace the System.Security.Cryptography.X509Certificates namespace.
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;
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();
}
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)
{
readData = "Conected to NYP Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
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)
{
// send text
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
//clear textsend textbox
textSend.Text = "";
}
private void textDisplay_TextChanged(object sender, EventArgs e)
{
textDisplay.SelectionStart = textDisplay.Text.Length;
textDisplay.ScrollToCaret();
textDisplay.Refresh();
}
}
}
Assign this event handler to the TextChanged event of the textbox and set the Enabled property of the button initially to false.
private void textSend_TextChanged(object sender, EventArgs e)
{
buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
}