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)
{
}
}
Related
My objective here to to send a message to the connected clients from my server. The code is working but the only problem is, it can only send message to the client who sent the command. What I need is to received the message by other client. I saw this code in youtube and make a few adjustment. Please find below.
Server Code
class Program
{
private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static readonly List<Socket> clientSockets = new List<Socket>();
private const int BUFFER_SIZE = 2048;
private const int PORT = 100;
private static readonly byte[] buffer = new byte[BUFFER_SIZE];
static void Main(string[] args)
{
Console.Title = "Server";
SetupServer();
Console.ReadLine(); // When we press enter close everything
CloseAllSockets();
}
private static void SetupServer()
{
Console.WriteLine("Setting up server...");
serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
serverSocket.Listen(0);
serverSocket.BeginAccept(AcceptCallback, null);
Console.WriteLine("Server setup complete");
}
/// <summary>
/// Close all connected client (we do not need to shutdown the server socket as its connections
/// are already closed with the clients).
/// </summary>
private static void CloseAllSockets()
{
foreach (Socket socket in clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
serverSocket.Close();
}
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException) // I can not seem to avoid this (on exit when properly closing sockets)
{
return;
}
clientSockets.Add(socket);
socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Console.WriteLine("{0}", socket.RemoteEndPoint + " connected...");
serverSocket.BeginAccept(AcceptCallback, null);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
// Don't shutdown because the socket may be disposed and its disconnected anyway.
current.Close();
clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
if (text.ToLower() == "meeting") // Client requested time
{
foreach (Socket socket in clientSockets)
{
//current = socket;
string message = "meeting";
byte[] data = Encoding.ASCII.GetBytes(message);
socket.Send(data);
//socket.BeginSend(data, 0, data.Length, SocketFlags.None, null, null);
Console.WriteLine("Meeting invite sent to " + socket.RemoteEndPoint);
}
}
else if (text.ToLower() == "exit") // Client wants to exit gracefully
{
// Always Shutdown before closing
Console.WriteLine(current.RemoteEndPoint + " disconnected");
current.Shutdown(SocketShutdown.Both);
current.Close();
clientSockets.Remove(current);
return;
}
else
{
Console.WriteLine("Invalid request");
byte[] data = Encoding.ASCII.GetBytes("Invalid request");
current.Send(data);
Console.WriteLine("Warning Sent");
}
current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
}
Client Code
namespace TCP_Client {
public partial class frmTCPClient : Form
{
private readonly Socket ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private const int PORT = 100;
private byte[] buffer;
private string message { get; set; }
public string serverMessage { get; set; }
public frmTCPClient()
{
InitializeComponent();
}
private void frmTCPClient_Load(object sender, EventArgs e)
{
ConnectToServer();
//UpdateControls();
}
private void UpdateControls()
{
lblMessage.Text = message;
//txtFromServer.Text = serverMessage;
}
private void ConnectToServer()
{
int attempts = 0;
while (!ClientSocket.Connected)
{
try
{
attempts++;
//lblMessage.Text = "Connection attempt " + attempts;
// Change IPAddress.Loopback to a remote IP to connect to a remote host.
//ClientSocket.Connect(IPAddress.Loopback, PORT);
ClientSocket.Connect("172.20.110.129", PORT);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + "Connection attempt " + attempts);
}
}
message = "Connected";
}
private void RequestLoop()
{
while (true)
{
SendRequest("");
ReceiveResponse();
}
}
private void SendRequest(string text)
{
string request = text;
SendString(request);
if (request.ToLower() == "exit")
{
Exit();
}
}
/// <summary>
/// Sends a string to the server with ASCII encoding.
/// </summary>
private void SendString(string text)
{
try
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
ClientSocket.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
SendRequest(txtMessage.Text);
ReceiveResponse();
UpdateControls();
}
private void Exit()
{
SendString("exit"); // Tell the server we are exiting
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
Environment.Exit(0);
}
public void ReceiveResponse()
{
var buffer = new byte[2048];
try
{
if (buffer.ToString().Length == 2048) return;
int received = ClientSocket.Receive(buffer, SocketFlags.None);
if (received == 0) return;
var data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
txtFromServer.Text += text + System.Environment.NewLine;
//MessageBox.Show(text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmTCPClient_FormClosed(object sender, FormClosedEventArgs e)
{
Exit();
}
} }
Update
foreach (object obj in clientSockets)
{
string message = "meeting";
byte[] data = Encoding.ASCII.GetBytes(message);
Socket socket = (Socket)obj;
socket.Send(data);
Console.WriteLine("Meeting invite sent to " + socket.RemoteEndPoint);
}
Image
enter image description here
//====================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'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();
}
This is my code for a simple chat program that works client to client. The problem is that when i click the send button an error is thrown.
The error is...
System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host at System.Net.Sockets.SocketEndRecieveFrom(IAsyncResult asyncResult, EndPoint& endPoint) at ChatClientV1.MainForm.MessageCallBack(IAsynResult aResult)...line 36 below which is ...
int size = sck.EndReceiveFrom(aResult, ref epRemote);
public MainForm()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//localIP = GetLocalIP();
//friendIP = GetLocalIP();
localIP = "192.168.0.17";
friendIP = "192.168.0.17";
friendPortNumber = "81";
localPortNumber = "80";
username = "Shawn";
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recieveData = new byte[1464];
recieveData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string recieveMessage = eEncoding.GetString(recieveData);
messageListBox.Items.Add(username+": "+recieveMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void currentSettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
CurrentSettingsFrom aCurrentSettingsForm = new CurrentSettingsFrom();
aCurrentSettingsForm.ShowDialog();
}
private void sendFileToolStripMenuItem_Click(object sender, EventArgs e)
{
SendFileForm aSendFileForm = new SendFileForm();
aSendFileForm.ShowDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void appearanceToolStripMenuItem_Click(object sender, EventArgs e)
{
AppearanceForm aAppearanceFrom = new AppearanceForm();
aAppearanceFrom.ShowDialog();
}
private void connectButton_Click(object sender, EventArgs e)
{
try
{
eplocal = new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPortNumber));
sck.Bind(eplocal);
epRemote = new IPEndPoint(IPAddress.Parse(friendIP), Convert.ToInt32(friendPortNumber));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
connectButton.Text = "Connected";
connectButton.Enabled = false;
sendMessageButton.Enabled = true;
messageEntryField.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void sendMessageButton_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(messageEntryField.Text);
sck.Send(msg);
messageListBox.Items.Add(username + ": " + messageEntryField.Text);
messageEntryField.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
host = Dns.GetHostEntry(Dns.GetHostName());
Due to this statement in the process of getting client ip, you are getting exception.
replace the code with
protected string GetClientIP()
{
string result = string.Empty;
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
result = ipRange[0];
}
else
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return result;
}
now you will not get that error.
You turned off the server in order listen request from clients. So try to turn on it if you have one or try to create a server in difference project and run it.
You can have an example here
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");
}
}
}
}