I'm pretty new to this, I just want to send a message from my console server window to the client.
Here's my server:
static void Main(string[] args)
{
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(localEndPoint);
newsock.Listen(10);
Socket client = newsock.Accept();
if (client.Connected)
{
Console.WriteLine("client connected.");
}
string msg = "Who's there?";
byte[] buffer = new byte[msg.Count()];
buffer = Encoding.ASCII.GetBytes(msg);
client.Send(buffer);
It works fine when i use client.Send() above, but when when I do as follows below I receive nothing on the other end. Since the client is connected, I see no reason why it fails.
while (client.Connected)
{
Console.WriteLine("enter msg: ");
string userMsg = Console.ReadLine();
byte[] userBuffer = new byte[userMsg.Count()];
userBuffer = Encoding.ASCII.GetBytes(userMsg);
client.Send(userBuffer);
Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
Here's the code for the client:
public partial class MainWindow : Window
{
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
byte[] buffer = new byte[12];
public MainWindow()
{
InitializeComponent();
}
private void btn_Connect_Click(object sender, RoutedEventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);
if (server.Connected)
{
txt_Log.AppendText("\nConnected to target server.");
}
btn.IsEnabled = false;
btn_disc.IsEnabled = true;
}
private void btn_Disconnect_Click(object sender, RoutedEventArgs e)
{
server.Close();
if (!server.Connected)
{
txt_Log.AppendText("\nDisconnected to target server.");
}
btn.IsEnabled = true;
btn_disc.IsEnabled = false;
}
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
}
Well I've run your server code. No problems there...
For the client, it seemed you dispose the server, which drops the connnection? and null the buffer, so you can't re-use that either....
I wrote some test client code which seemed to work fine
class Program
{
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect("127.0.0.1", 8000);
byte[] buffer = new byte[1024];
while (true)
{
int bytes = server.Receive(buffer);
Console.WriteLine(System.Text.Encoding.Default.GetString(buffer, 0, bytes));
}
}
}
Note that the point of this you don't disconnect the client every time you read a packet, and if you null your static before and then null check it is going to be null so fetch will only work once, therefore don't do it!
Also as Mark said, check the number of bytes read from the call the Receive so you can tell how many bytes to decode.
Change
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
To..
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
and call dispose when the window is closed
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
server.Dispose();
}
Related
I have a small server that is received and sends the message back to the client.
this is the client-side
when I open the client it will connect to server through Connect()
public Form1()
{
InitializeComponent();
Connect();
CheckForIllegalCrossThreadCalls = false;
}
this is my connect
void Connect()
{
ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipep);
}
catch (SocketException e)
{
MessageBox.Show(Convert.ToString(e));
}
Thread listen = new Thread(Receive);
listen.IsBackground = true; ;
listen.Start();
}
and I have a receive like this
void Receive()
{
datarec = new byte[1024];
try
{
while (true)
{
string StringData;
rec = server.Receive(datarec);
StringData = Encoding.ASCII.GetString(data, 0, rec);
txtShow.Text = StringData;
}
}
catch
{
Close();
}
}
and I send data through a button have Send method
void Send(string s)
{
data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
server.Send(data, data.Length, SocketFlags.None);
}
Send button
private void button1_Click(object sender, EventArgs e)
{
string s = txtText.Text;
Send(s);
}
this is the server-side
I have a thread server
public static void Process(Socket client)
{
byte[] data = new byte[1024];
int recv;
string dataInput;
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
while (true)
{
try
{
recv = client.Receive(data);
dataInput = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(dataInput);
client.Send(data);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
}
this is the server main
public static void Main()
{
byte[] rec = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9999);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
Console.WriteLine("Waiting for client...");
Console.WriteLine("LOG CHAT");
while (true)
{
Socket client = server.Accept();
Core core = new Core();
Thread t = new Thread(() => Core.Process(client));
t.Start();
}
}
the server receive message but when it sends a message back it has an error "An established connection was aborted by the software in your host machine"
Can you guys tell me where I was wrong and how can I fix it?
When you call client.Send(data) in your server code, you will send the whole 1024 byte buffer back to the client, not just the data received.
Encoding.ASCII.GetString in the client could fail when processing this garbage and the exception will close the connection.
Try to replace client.Send(data) by client.Send(data, recv, SocketFlags.None).
Also, you should not update UI controls directly from a background thread, Use Control.Invoke for this. Failing to do so will also throw an exception and close the connection.
//====================Solution found================//
Problem : I have a problem whereby my server program cannot acknowledge another message sent from the client .The first one does though . I'm new to c# , therefore i might have less ideas on how best to achieve this .
Current work : Few things I've done so far were sockets in both server and client program , using backgroundworker and delegates .
So here's the scenario :
client program named KipaSusaMati
server program named Asynchronous Server + Mqtt
Server program were run first , then the client . The client supposedly able to send multiple messages to the port without fail,which the server listened to and take those messages and do something(repetitively).
//-----Server coding----//
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Start Server")
{
listBox1.Items.Add("======================================");
listBox1.Items.Add("Starting server");
changeServerButton(button1);//mok stop
backgroundWorker1.RunWorkerAsync();
}
else
{
listBox1.Items.Add(" Stopping server ....");
changeServerButtonStop(button1);
try
{
if (sListener.Connected)
{
sListener.Shutdown(SocketShutdown.Receive);
sListener.Close();
listBox1.Items.Add(DateTime.Now + " Server Disconnected");
}
else {
listBox1.Items.Add("Socket not in use . Cannot stop socket .");
listBox1.Items.Add(" Press EXIT to exit application. ");
button1.Enabled = false;
button3.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
permission = new SocketPermission(NetworkAccess.Accept,TransportType.Tcp,"localhost",11000);
sListener = null;
permission.Demand();
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
ipEndPoint = new IPEndPoint(ipAddr, 11000);
sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sListener.Bind(ipEndPoint);
sListener.Listen(1);
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = null;
Socket handler = null;
try
{
byte[] buffer = new byte[1024];
listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
handler.NoDelay = false;
object[] obj = new object[2];
obj[0] = buffer;
obj[1] = handler;
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), obj);
AsyncCallback aCallBack = new AsyncCallback(AcceptCallback);
listener.BeginAccept(aCallBack, listener);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
string stx = "0x02";
string etx = "0x03";
try
{
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
byte[] buffer = (byte[])obj[0];
handler = (Socket)obj[1];
string content = string.Empty;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
content += Encoding.Unicode.GetString(buffer, 0,
bytesRead);
// If message contains "<Client Quit>", finish receiving
if (content.IndexOf("<Client Quit>") > -1)
{
// Convert byte array to string
string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));
Console.WriteLine("Bytes from client :"+str);
if (content.IndexOf(stx) > -1)
{
Console.WriteLine("STX were detected");
}
else {
Console.WriteLine("STX were not detected");
}
}
else
{
// Continues to asynchronously receive data
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallBack), obj);
}
printMessage(content);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//------Client Coding---------//
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text != "BEGIN")
{
this.Dispose();
listBox1.Items.Add(" Disposing and STOP the application");
}
else
groupboxEnableAll();
listBox1.Items.Add("" + DateTime.Now + " Socket initiated.");
backgroundWorker1.RunWorkerAsync();
button1.Text = "STOP";
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
SocketPermission permission1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "localhost", 11000);
permission1.Demand();
senderSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
senderSock.NoDelay = false;
senderSock.Connect(localEndPoint);
Console.WriteLine("SenderSock rawkkkks!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
listBox1.Items.Add(""+DateTime.Now+" Socket started at port "+port);
}
client-server
From the picture , for the first iteration server managed to get the message sent by client , but for the next iteration , it never displayed .
Solution : Kindly take a look ReceiveCallBack method , instead of doing try catch,im doing do while loop to catch any incoming databytes .
private void ReceiveCallBack(IAsyncResult ar)
{
Console.WriteLine("in ReceiveCallback");
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
byte[] buffer = (byte[])obj[0];
handler = (Socket)obj[1];
string content = string.Empty;
int bytesRead = handler.EndReceive(ar);
do
{
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallBack), obj);
}
while (bytesRead < 0);
content += Encoding.Unicode.GetString(buffer, 0,bytesRead);
printMessage(content);
}
Hope others can benefitting from this .Thanks.
I have the following client/ server code in C#, I tested on two computers, they can connect successfully and does not have any problem with the connection
The Problem: when I try sending messages between them, sometimes the message will not be received on the destination computer until them destination send back a message.
Any help is appropriated..
Server:::
public partial class Form1 : Form
{
private byte[] data = new byte[1024];
private int size = 1024;
private Socket server;
private Socket client ;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
stopListining.Enabled = false;
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
private void startListining_Click(object sender, EventArgs e)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 20916);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
startListining.Enabled = false;
stopListining.Enabled = true;
}
private void stopListining_Click(object sender, EventArgs e)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
stopListining.Enabled = false;
startListining.Enabled = true;
}
void AcceptConn(IAsyncResult iar)
{
Socket server = (Socket)iar.AsyncState;
client = server.EndAccept(iar);
conStatuss("Connected to: " + client.RemoteEndPoint.ToString());
string stringData = "Server:: Welcome to my server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
try
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
conStatuss("Waiting for client...");
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
addResult(receivedData+"\"R("+DateTime.Now.ToString("h:mm:ss tt")+")\"");
//to send back received text
/*
byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
*/
}
catch (Exception eee)
{
conStatuss(eee.ToString());
}
}
delegate void SetTextCallback(string text);
private void conStatuss(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.statetxt.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(conStatuss);
this.Invoke(d, new object[] { text });
}
else
{
this.statetxt.Text = text;
}
}
public delegate void AddListBoxItem(string message);
public void addResult(string message)
{
//TODO: find out whats going on here
if (resultss.InvokeRequired)
{
//TODO: Which works better?
//AddListBoxItem albi = AddString;
//listBox.Invoke( albi, message );
resultss.Invoke(new AddListBoxItem(addResult), message);
}
else
this.resultss.Items.Add(message);
}
private void sendButton_Click(object sender, EventArgs e)
{
if (messageTXT.Text.Trim().ToString().Length == 0)
{
conStatuss("Write something to send!");
return;
}
/*
byte[] byData = System.Text.Encoding.ASCII.GetBytes(messageTXT.Text);
client.Send(byData);
resultss.Items.Add("Server:: "+messageTXT.Text);
*/
string stringData = "Server:: " + messageTXT.Text+"\"S("+DateTime.Now.ToString("h:mm:ss tt")+")\"";
addResult(stringData);
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
messageTXT.Clear();
}
}
Client:::
public partial class Form1 : Form
{
private TextBox newText;
private TextBox conStatus;
private ListBox results;
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
public Form1()
{
InitializeComponent();
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.10.4"), 20916);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
if (newText.Text.Trim().ToString().Length == 0)
{
conStatuss("Write something to send!");
return;
}
byte[] message = Encoding.ASCII.GetBytes("Client:: " + newText.Text + "\"S(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
addResult("Client:: " + newText.Text + "\"S(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
//client.Send(message);
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
newText.Clear();
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatuss("Connected to: " + client.RemoteEndPoint.ToString());
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
conStatuss("Error connecting");
}
}
void ReceiveData(IAsyncResult iar)
{
try
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
addResult(stringData + "\"R(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
/*
//to send back received text
byte[] message2 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
*/
}
catch (Exception eee)
{
conStatuss(eee.ToString());
}
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int sent = remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
delegate void SetTextCallback(string text);
private void conStatuss(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.conStatus.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(conStatuss);
this.Invoke(d, new object[] { text });
}
else
{
this.conStatus.Text = text;
}
}
public delegate void AddListBoxItem(string message);
public void addResult(string message)
{
//TODO: find out whats going on here
if (results.InvokeRequired)
{
//TODO: Which works better?
//AddListBoxItem albi = AddString;
//listBox.Invoke( albi, message );
results.Invoke(new AddListBoxItem(addResult), message);
}
else
this.results.Items.Add(message);
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
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
I have trouble in sending an object through socket in c#, my client can send to server but server can't send to client, i think there is something wrong with the client.
Server
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
Thread a = new Thread(connect);
a.Start();
}
private void sendButton_Click(object sender, EventArgs e)
{
client.Send(SerializeData(ShapeList[ShapeList.Count - 1]));
}
void connect()
{
try
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
server.Bind(iep);
server.Listen(10);
client = server.Accept();
while (true)
{
byte[] data = new byte[1024];
client.Receive(data);
PaintObject a = (PaintObject)DeserializeData(data);
ShapeList.Add(a);
Invalidate();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
client
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
Thread a = new Thread(connect);
a.Start();
}
private void SendButton_Click(object sender, EventArgs e)
{
client.Send(SerializeData(ShapeList[ShapeList.Count - 1]));
}
void connect()
{
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
client.Connect(iep);
while (true)
{
byte[] data = new byte[1024];
client.Receive(data);
PaintObject a = (PaintObject)DeserializeData(data);
ShapeList.Add(a);
Invalidate();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
CheckForIllegalCrossThreadCalls = false;
Remove this and fix the errors that pop up. If you suppress the errors, it's even harder to fix them.
client = server.Accept();
Is in one thread:
client.Send(SerializeData(ShapeList[ShapeList.Count - 1]));
Is in the UI thread.
That's not threadsafe.
You have your client receiving data in a loop, when do you want to send? I'd suggest adding to a threadsafe queue in the click (http://msdn.microsoft.com/en-us/library/dd267265(v=vs.110).aspx) and when it's suitable send in the loop:
while (true)
{
byte[] data = new byte[1024];
var received = client.Receive(data);
if(received > 0)
{ //careful, how do you know you have it all?
PaintObject a = (PaintObject)DeserializeData(data);
ShapeList.Add(a);
Invalidate();
}
if(!queue.IsEmpty)
{
//queue dequeue and send
client.Send(...);
}
}
Fuller example
//threadsafe queue
private readonly ConcurrentQueue<byte[]> queue = new ConcurrentQueue<byte[]>();
private void SendButton_Click(object sender, EventArgs e)
{
//queue it up
queue.Enqueue(SerializeData(ShapeList[ShapeList.Count - 1]));
}
void connect()
{
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
client.Connect(iep);
while (true)
{
byte[] data = new byte[1024];
var received = client.Receive(data);
if(received > 0)
{ //careful, how do you know you have it all?
PaintObject a = (PaintObject)DeserializeData(data);
ShapeList.Add(a);
Invalidate();
}
while(!queue.IsEmpty)
{
//queue dequeue and send
client.Send(queue.Dequeue());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a homework to build an application which will send and receive simple string between server and client. I know how to establish connection, but don't know how to send and receive string. This is my code :
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
// I want to use this method for both buttons : "send button" on server side and "send button"
// on client side. First I read text from textbox2 on server side or textbox3
// on client side than accept and write the string to label2(s) or label3(c).
//
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
}
listener.Stop();
Console.ReadLine();
}
In addition to #Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
byte[] bufferReceive = new byte[4096];
byte[] bufferSend = new byte[4096];
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
while (true)
{
int length = socket.Receive(bufferReceive);
if (length > 0)
{
label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
while (true)
{
NetworkStream nts = client.GetStream();
int length;
while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
{
label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
if (socket!=null)
{
bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
socket.Send(bufferSend);
}
else
{
if (client.Connected)
{
bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
NetworkStream nts = client.GetStream();
if (nts.CanWrite)
{
nts.Write(bufferSend,0,bufferSend.Length);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
bool SendReceiveTCP(string ipAddress, string sendMsg, ref string recMsg)
{
try
{
DateTime startTime=new DateTime();
TcpClient clt = new TcpClient();
clt.Connect(ipAddress, 8001);
NetworkStream nts = clt.GetStream();
nts.Write(Encoding.ASCII.GetBytes(sendMsg),0, sendMsg.Length);
startTime = DateTime.Now;
while (true)
{
if (nts.DataAvailable)
{
byte[] tmpBuff = new byte[1024];
System.Threading.Thread.Sleep(100);
int readOut=nts.Read(tmpBuff, 0, 1024);
if (readOut > 0)
{
recMsg = Encoding.ASCII.GetString(tmpBuff, 0, readOut);
nts.Close();
clt.Close();
return true;
}
else
{
nts.Close();
clt.Close();
return false;
}
}
TimeSpan tps = DateTime.Now - startTime;
if (tps.TotalMilliseconds > 2000)
{
nts.Close();
clt.Close();
return false;
}
System.Threading.Thread.Sleep(50);
}
}
catch (Exception ex)
{
throw ex;
}
}
CLIENT
namespace SocketKlient
{
class Program
{
static Socket Klient;
static IPEndPoint endPoint;
static void Main(string[] args)
{
Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string command;
Console.WriteLine("Write IP address");
command = Console.ReadLine();
IPAddress Address;
while(!IPAddress.TryParse(command, out Address))
{
Console.WriteLine("wrong IP format");
command = Console.ReadLine();
}
Console.WriteLine("Write port");
command = Console.ReadLine();
int port;
while (!int.TryParse(command, out port) && port > 0)
{
Console.WriteLine("Wrong port number");
command = Console.ReadLine();
}
endPoint = new IPEndPoint(Address, port);
ConnectC(Address, port);
while(Klient.Connected)
{
Console.ReadLine();
Odesli();
}
}
public static void ConnectC(IPAddress ip, int port)
{
IPEndPoint endPoint = new IPEndPoint(ip, port);
Console.WriteLine("Connecting...");
try
{
Klient.Connect(endPoint);
Console.WriteLine("Connected!");
}
catch
{
Console.WriteLine("Connection fail!");
return;
}
Task t = new Task(WaitForMessages);
t.Start();
}
public static void SendM()
{
string message = "Actualy date is " + DateTime.Now;
byte[] buffer = Encoding.UTF8.GetBytes(message);
Console.WriteLine("Sending: " + message);
Klient.Send(buffer);
}
public static void WaitForMessages()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer");
Klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}
Server:
namespace SocketServer
{
class Program
{
static Socket klient;
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
server.Bind(endPoint);
server.Listen(20);
while(true)
{
Console.WriteLine("Waiting...");
klient = server.Accept();
Console.WriteLine("Client connected");
Task t = new Task(ServisClient);
t.Start();
}
}
static void ServisClient()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer...");
klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
string answer = "Actualy date is " + DateTime.Now;
buffer = Encoding.UTF8.GetBytes(answer);
Console.WriteLine("Sending {0}", answer);
klient.Send(buffer);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}