Client cannot send another message to server - c#

//====================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.

Related

clients cannot establish connection after certain time even if the socket server is running

I have a console application which acts as a socket server. It should accept data 24/7 from a number of clients, but issue is that the clients cannot establish connection after sometime (not constant). after closing & opening the connection works & it continues to next point of time.
Server
public static void ExecuteServer()
{
int portNumber = 11111;
string _responseMessageToClient = "";
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
bool doBroadCast = false;
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
try`enter code here`
{
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024*2];//2048
string data = null;
while (true)
{
try
{
if (clientSocket.Connected)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("!") > -1)
break;
}
else
{
Console.WriteLine("Disconnected {0}", clientSocket.LocalEndPoint);
break;
}
}
catch (Exception e)
{
//ErrorLogProvider.Save(e);
Console.WriteLine(e.ToString());
break;
}
}
Console.WriteLine("Text received -> {0} ", data);
if (clientSocket.Connected)
{
clientSocket.Send(message);
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
This server has to be running continuously - Client code given below
static void ExecuteClient()
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
int portNumber = 11111;
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
long i = 0;
try
{
//while (i < 10)
//{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("^check!");
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
//}
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I've got this code somewhere from SO if I remember that correctly.
LoopClients just checks for new clients and handles them by spawning a new thread.
class Server {
private TcpListener _server;
private Boolean _isRunning = true;
private int m_Port = 12001;
private Thread m_ServerThread;
public Server (int p_Port) {
_server = new TcpListener(IPAddress.Any, m_Port);
_server.Start( );
m_ServerThread = new Thread(new ThreadStart(LoopClients));
m_ServerThread.Start( );
}
public void ShutdownServer() {
_isRunning = false;
}
public void LoopClients ( ) {
while ( _isRunning ) {
// wait for client connection
TcpClient newClient = _server.AcceptTcpClient( );
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
public void HandleClient (object obj) {
try {
// retrieve client from parameter passed to thread
TcpClient client = (TcpClient) obj;
// sets two streams
StreamWriter sWriter = new StreamWriter(client.GetStream( ), Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream( ), Encoding.ASCII);
// you could use the NetworkStream to read and write,
// but there is no forcing flush, even when requested
String sData = null;
while ( client.Connected ) {
sData = sReader.ReadToEnd( );
if ( sData != "" )
break;
}
try {
sWriter.WriteLine("test");
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
sWriter.Dispose( );
sReader.Dispose( );
sWriter = null;
sReader = null;
} catch ( IOException ioe ) {
}
}
}
Client is somewhat shorter. I've got to shorten the code a bit here.
Client:
private void sendDataViaTCP () {
TcpClient l_Client = new TcpClient();
l_Client.Connect(IP, Port);
Stream l_Stream = l_Client.GetStream( );
StreamWriter l_SW = new StreamWriter(l_Stream);
StreamReader l_SR = new StreamReader(l_SW.BaseStream);
try {
l_SW.WriteLine(Msg);
l_SW.Flush( );
String l_IncomingData;
while ( ( l_IncomingData = l_SR.ReadToEnd()) != "") {
AddLineToLog(l_IncomingData);
}
} finally {
l_SW.Close( );
}
}

Send byte[] continuously from server to client?

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();
}

System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host

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

console window starts behind gui

I have created a gui for server but whenever I start gui a console window also opens and if I close console window the gui also closes. The console window doesn't do anything it just opens when I start my gui. How can I avoid this? I want only gui to start and not console window.
namespace ServerUI
{
public partial class Server : Form
{
public Server()
{
InitializeComponent();
//default port number
textBox1.Text = "8001";
button1.Click += button1_Click;
}
//Global Variables
public static class Globals
{
public const string IP = "127.0.0.1";
public static int port_number = 0;
public static string selected = "";
public static string selected_1 = "";
}
//IP address of server
static IPAddress ipAddress = IPAddress.Parse(Globals.IP);
//List of active clients connected to server
List<Socket> active_clients = new List<Socket>();
static Socket serverSocket;
static byte[] buffer = new Byte[1024];
public static ManualResetEvent allDone = new ManualResetEvent(false);
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text.Trim()))
{
System.Windows.Forms.MessageBox.Show("Port Number Empty", "Error");
return;
}
else
{
bool check = int.TryParse(textBox1.Text, out Globals.port_number);
if (!check)
{
MessageBox.Show("Port Number not in correct format. Enter Port Number again", "Error");
return;
}
client_pkt_parsing.client_list.Clear();
foreach (DataGridViewRow myRow in dataGridView1.Rows)
{
myRow.Cells[1].Value = null; // assuming you want to clear the first column
}
foreach (DataGridViewRow myRow in dataGridView2.Rows)
{
myRow.Cells[1].Value = null; // assuming you want to clear the first column
}
//Starting Server
StartServer();
}
} //end of button1_Click
public void StartServer()
{
byte[] bytes = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Globals.port_number);
try
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(10);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
infoBox.Text = "Server started. Waiting for a connection...";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}//end of StartServer
public void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
try
{
Socket clientSocket = serverSocket.EndAccept(ar);
infoBox.Text = infoBox.Text + "\r\n" + string.Format(DateTime.Now.ToString("HH:mm:ss") + " > Client : " + clientSocket.RemoteEndPoint.ToString() + "connected");
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (Exception ex)
{
}
}//end of AcceptCallback
public void ReceiveCallback(IAsyncResult ar)
{
try
{
int received = 0;
Socket current = (Socket)ar.AsyncState;
received = current.EndReceive(ar);
byte[] data = new byte[received];
if (received == 0)
{
return;
}
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
testBox.Text = testBox.Text + "\r\n" + text;
//Send(current, "hello");
buffer = null;
Array.Resize(ref buffer, current.ReceiveBufferSize);
current.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), current);
}
catch (Exception ex)
{
}
}//end of RecieveCallback
}
}
This typically happens when you started with the wrong project template. It is fixable. Use Project + Properties, Application tab. Change the "Output type" setting from Console Application to Windows Application. No more console.

Server Client send/receive simple text

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");
}
}
}
}

Categories

Resources