I am trying to convert an existing C# console app code to a C# winform the code below works well.
class Program
{
const int PORT_NO = 49211;
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();
}
}
But when i tried to convert this into a winform app, the application freeze until i manually stop in on Visual Studio. I Attached it into a button click event.
const int PORT_NO = 49211;
const string SERVER_IP = "127.0.0.1";
private void button1_Click(object sender, EventArgs e)
{
//---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---
lstProgress.Items.Add("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);
lstProgress.Items.Add("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
client.Close();
}
Any suggestion would be great thanks in advance!
Related
Simple question, but after weeks of search no luck. I need to create a server-client program. Everything works well with localhost, but I need it over the internet. I work under Linux (Ubuntu).
Server:
public class SocketServer
{
private const int PORT_NO = 8001;
public SocketServer()
{
//---listen at the specified IP and port no.---
var listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Socket server started.");
listener.Start();
while (true)
{
//---incoming client connected---
var client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
var nwStream = client.GetStream();
var buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
var bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"{dataReceived}");
client.Close();
}
}
}
Client code:
public class Client
{
private const int PORT_NO = 8001;
private const string SERVER_IP = "xxx.xx.246.1";
public void Run()
{
while (true)
{
var textToSend = Console.ReadLine();
//---create a TCPClient object at the IP and port no.---
var client = new TcpClient(SERVER_IP, PORT_NO);
var nwStream = client.GetStream();
var bytesToSend = Encoding.ASCII.GetBytes(textToSend ?? string.Empty);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
For IP I used www.whatsmyip.org, and I got an error:
System.Net.Sockets.SocketException (0x80004005): Connection refused
What am I missing? Is there some real example, no just with localhost?
I have a function I use for sending a message to a server. The server returns a string like 'true' or 'false' and the client returns the value returned by the server. My problem is that when I call ClientReturn with my request I get my return in the function but not into another function string or if(ClientReturn() == "false / true") is empty.
public static string ClientReturn(string ip, int port, string message)
{
string toReturn = "";
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate (object s, DoWorkEventArgs args)
{
//---data to send to the server---
string textToSend = message;
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(ip, port);
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);
toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
Console.WriteLine("Returned: " + toReturn); //It's the return of the server
client.Close();
};
worker.RunWorkerAsync();
return toReturn; //Return the value but not work it's return nothing
}
The problem is that you are not waiting for the BackgroundWorker to complete.
To be honest, BackgroundWorker is obsolete anyway. Instead use async and await.
You are also missing using blocks to dispose the client and stream.
public static async Task<string> ClientReturn(string ip, int port, string textToSend)
{
//---create a TCPClient object at the IP and port no.---
using (TcpClient client = new TcpClient())
{
await client.ConnectAsync(ip, port);
using (NetworkStream nwStream = client.GetStream())
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);
var toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
Console.WriteLine("Returned: " + toReturn); //It's the return of the server
return toReturn; //Return the value but not work it's return nothing
};
}
}
All i want to do is send message to client from server. I try a lot of tutorial etc. but still can't send message from server to client.
Send from client to server is simple and have it in code. When client Send "HI" to server i want to respond Hi to client. But dunno what should i add to my code. Can someone help me with that? Please don't do it like duplicate i know there is a lot of similar topic but can't find solution.
Server code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
};
while (true)
{
client = server.AcceptTcpClient();
byte[] receivetBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivetBuffer, 0, receivetBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach(byte b in receivetBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
////Resive message :
if (msg.ToString() =="HI")
{
///#EDIT 1
///// HERE Is SENDING MESSAGE TO CLIENT//////////
int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
stream.Write(sendData, 0, sendData.Length);
}
}
Client code:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string serverIP = "localhost";
int port = Convert.ToInt32(8555);
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("HI" + ";");
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
///////////////////////////////HERE I WANT A read message from server/
/////////////////////////////////////////////////////////////////////
stream.Close();
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
}
Try this Here is my version of client and server ,feel free to ask if any reference problem ,the client wait for server to (online) then if server is online connect with it.
Method to Connect with Server
private void Connectwithserver(ref TcpClient client)
{
try
{
//this is server ip and server listen port
server = new TcpClient("192.168.100.7", 8080);
}
catch (SocketException ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
RunBoTClient();
}
}
byte[] data = new byte[1024];
string stringData;
TcpClient client;
private void RunClient()
{
NetworkStream ns;
Connectwithserver(ref client);
while (true)
{
ns = client.GetStream();
//old
// ns.ReadTimeout = 50000;
//old
ns.ReadTimeout = 50000;
ns.WriteTimeout = 50000;
int recv = default(int);
try
{
recv = ns.Read(data, 0, data.Length);
}
catch (Exception ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
//try to reconnect if server not respond
RunClient();
}
//READ SERVER RESPONSE/MESSAGE
stringData = Encoding.ASCII.GetString(data, 0, recv);
}
}
Server
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);
//IF YOU WANT TO WRITE BACK TO CLIENT USE
string yourmessage = console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
//---write back the text to the client---
Console.WriteLine("Sending back : " + yourmessage );
nwStream.Write(sendBytes, 0, sendBytes.Length);
client.Close();
}
listener.Stop();
I'm extremely new to any type of networking with programming. When trying to create a simple socket server program I get the following error:
Specified argument was out of the range of valid values.
Parameter name: size
Here is my code for the server:
class Program
{
private static IPAddress localServerIP = IPAddress.Parse("10.114.130.223");
private static TcpListener serverSocket;
private static TcpClient clientSocket;
private static int requestCount = 0;
static void Main(string[] args)
{
serverSocket = new TcpListener(localServerIP, 8888);
clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started\n");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while (true)
{
try
{
requestCount++;
NetworkStream networkStream = clientSocket.GetStream();
byte[] dataBuffer = new byte[10025];
networkStream.Read(dataBuffer, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(dataBuffer);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
And this is my client
public partial class Form1 : Form
{
private TcpClient clientSocket;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket = new TcpClient();
try
{
clientSocket.Connect(IPAddress.Parse("10.114.130.223"), 8888);
}
catch
{
textBox1.AppendText(" >> Server unavailable\n");
}
statusLabel.Text = "Client Socket Program - Server Connected";
}
private void sendBtn_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returnData = Encoding.ASCII.GetString(inStream);
msg(returnData);
textBox2.Text = "";
textBox2.Focus();
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
Any help or guidance or explanation would greatly be appreciated.
It's either from
networkStream.Read(dataBuffer, 0, (int)clientSocket.ReceiveBufferSize);
or from
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Read the docs for NetworkStream.Read Exceptions and for substring exceptions.
I am trying to receive data from an app connected to my server but it is sending the data as null?
//Receive Data
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string ReserveText = Encoding.ASCII.GetString(dataBuf);
//Write to Console if no error appears
Console.WriteLine("Message received from client: " + ReserveText);
It is currently printing Message received from client: and it is ment to print the 'ReserveText' after it but the reserve test is obviously empty? The above code is my server code and below I have shared the full void and the code in the client.
Full Void:
public void ReceiveCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
string clientIP = socket.RemoteEndPoint.ToString();
try
{
//Receive Data
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string ReserveText = Encoding.ASCII.GetString(dataBuf);
//Write to Console if no error appears
Console.WriteLine("Message received from client: " + ReserveText);
string ResponceText = "Testing Response";
byte[] data = Encoding.ASCII.GetBytes(ResponceText);
//socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
SendAsync(socket, data, 0, data.Length);
Console.WriteLine("Message sent to client: " + ResponceText);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback),
socket);
}
catch (Exception)
{
Console.WriteLine("Client Disconnected");
//TODO: DISPOSE THE SOCKET/SESSION FROM _clients
}
}
Here is the method on the client side SENDING to the server
public static string SendMessageAndReturnResponse(string req)
{
byte[] buffer = Encoding.ASCII.GetBytes(req);
_clientSocket.Send(buffer);
byte[] receivedBuf = new byte[1024];
int rec = _clientSocket.Receive(receivedBuf);
byte[] data = new byte[rec];
Array.Copy(receivedBuf, data, rec);
return Encoding.ASCII.GetString(data);
}