I try to make the LAN chat application, use Send() and Receive() function in C# to send and receive message. But the problem is that, when user type in message into Console and press Enter keyboard, this content suddenly appear in Console Screen before WriteLine my form appear (For example: what I expected is You: hello)
How could I remove line "hello". What I expecting is:
Client: hi
You: hello
Code for Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpSrvr
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",clientep.Address,clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.UTF8.GetBytes(welcome);
client.Send(data,data.Length,SocketFlags.None);
string input;
while (true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine("Client: "+Encoding.UTF8.GetString(data, 0, recv));
input = Console.ReadLine();
Console.WriteLine("You: " + input);
client.Send(Encoding.UTF8.GetBytes(input));
}
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
newsock.Close();
Console.ReadLine();
}
}
}
Code for Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpClient
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
server.Connect(ipep);
}
catch(SocketException e)
{
Console.WriteLine("Unable to connect to server.");
Console.WriteLine(e.ToString());
return;
}
int recv = server.Receive(data);
stringData = Encoding.UTF8.GetString(data, 0, recv);
Console.WriteLine(stringData);
while (true)
{
input = Console.ReadLine();
if (input == "exit")
break;
Console.WriteLine("You: " + input);
server.Send(Encoding.UTF8.GetBytes(input));
data = new byte[1024];
recv = server.Receive(data);
stringData = Encoding.UTF8.GetString(data, 0, recv);
byte[] utf8string = System.Text.Encoding.UTF8.GetBytes(stringData);
Console.WriteLine("Server: "+stringData);
}
Console.WriteLine("Disconnecting from server...");
server.Shutdown(SocketShutdown.Both);
server.Close();
Console.WriteLine("Disconnected!");
Console.ReadLine();
}
}
}
Thanks everyone!
You could try this, Set the cursor position back to the start of the previous line after ReadLine & then overwrite the line with your text - in your case as you are prepending "You: " your output string will be longer than the input string - if it were smaller you could overwrite with spaces to clear any excess characters.
input = Console.ReadLine();
Console.SetCursorPosition(0, Console.CursorTop-1);
Console.WriteLine("You: " + input);
Related
So i got this multi thread tcp server code, it is working great, but i can not switch between clients.
So my question is how can i switch between clients?
I am planing to switch the server to winforms but i do not know how to access other threads.
Also, please tell what should i improve and better ways of sanitizing user input.
Here is the server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
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);
//---prepare client counter---
int num = 0;
//---announce and start listening---
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
//---add 1 to total clients---
num = num + 1;
//---check if current thread name is null, if yes set the current client position---
if (Thread.CurrentThread.Name == null)
{
Thread.CurrentThread.Name = num.ToString();
}
else
{
Console.WriteLine("Unable to name a previously " +
"named thread.");
}
string clientip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
//---write that client connected and write its ip---
Console.WriteLine("Client connected: [IP: {0}, Client: {1}]", clientip, Thread.CurrentThread.Name);
//---loop for infinite amount of time---
while (true)
{
try
{
//---Make thread background---
Thread.CurrentThread.IsBackground = true;
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
new Thread(() =>
{
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("[IP: {0}, Client: {1}]: " + dataReceived, clientip, Thread.CurrentThread.Name);
}).Start();
//---write back the text to the client---
Console.WriteLine("Enter data to send back to [IP: {0}, Client: {1}]: ", clientip, Thread.CurrentThread.Name);
//---read user input---
string input = Console.ReadLine();
//---sanitize user input---
if (input == String.Empty)
{
input = #" ";
}
if (input == #"")
{
input = #" ";
}
if (input == null)
{
input = #" ";
}
//---convert ASCII text to bytes---
byte[] send = Encoding.ASCII.GetBytes(input);
//---write bytes to network stream---
nwStream.Write(send, 0, send.Length);
}
catch (Exception)
{
//---close client---
client.Close();
//---Announce disconnect---
Console.WriteLine("Client disconnected [IP: {0}, Client: {1}]", clientip, Thread.CurrentThread.Name);
//---remove 1 from total clients---
num = num - 1;
//---Abort current thread---
Thread.CurrentThread.Abort();
return;
}
}
}).Start();
}
}
}
}
This is the code for client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
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 = "Received the text.";
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
while (true)
{
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));
}
client.Close();
}
}
}
I am UsingClient.Send(Encoding.ASCII.GetBytes(Message)); to send a message to the client, when i tried sending a second message it doesn't give any error so i think it send with no problem but it never reaches the client (127.0.0.1)
Code That Send
public void SendMessage(Socket _Client, string Message)
{
foreach (Socket Client in Clients)
{
IPEndPoint TargetEndPoint = _Client.LocalEndPoint as IPEndPoint;
IPAddress TargetIp = TargetEndPoint.Address;
int TargetPort = TargetEndPoint.Port;
IPEndPoint ClientEndPoint = Client.LocalEndPoint as IPEndPoint;
IPAddress ClientIp = ClientEndPoint.Address;
int ClientPort = ClientEndPoint.Port;
if (TargetIp.ToString() == ClientIp.ToString() && TargetPort == ClientPort)
{
Client.Send(Encoding.ASCII.GetBytes(Message));
//Client.EndSend();
}
}
}
Code That Receive
private void RecivedCallBack(IAsyncResult Result)
{
//Create a int with the Buffer Size
int BufferSize = _Socket.EndReceive(Result);
//Create a new byte array with the Buffer Size
byte[] Packet = new byte[BufferSize];
//Copy Buffer to Packet
Array.Copy(_Buffer, Packet, Packet.Length);
//Handle Packet
PacketHandler.Packet(Encoding.UTF8.GetString(Packet));
//Makes _Buffer a new byte
_Buffer = new byte[1024];
//Get Ready to recive data
_Socket.BeginReceive(_Buffer, 0, _Buffer.Length, SocketFlags.None, RecivedCallBack, null);
}
Code that Handle
public static void Packet(string Message)
{
Console.WriteLine(Message);
switch (Message)
{
case "StartChat":
_ChatForm Start = new _ChatForm();
Start.ShowDialog();
break;
case "StopChat":
_ChatForm._Chat.EndChat();
break;
}
}
TCP is stream based, so your client has no way to know when the message has ended. Either use UDP, implement a way to detect the end of messages (eg send a 4 byte message with the length of the real message, before sending the real message... and read on the client until the whole message has been received), or use a library. I like Hazel: https://github.com/DarkRiftNetworking/Hazel-Networking.
The great thing about Hazel is that it implements reliable UDP. So, if you need to have your "messages" arrive in the order in which they were sent, or if you need guaranteed delivery and receipt of such messages (such as what TCP provides), then you can do so with their reliable UDP implementation.
They will also implement Web Sockets at some point :) Good luck!
A client/server example from the documentation:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Hazel;
using Hazel.Tcp;
namespace HazelExample
{
class ServerExample
{
static ConnectionListener listener;
public static void Main(string[] args)
{
listener = new TcpConnectionListener(IPAddress.Any, 4296);
listener.NewConnection += NewConnectionHandler;
Console.WriteLine("Starting server!");
listener.Start();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
listener.Close();
}
static void NewConnectionHandler(object sender, NewConnectionEventArgs args)
{
Console.WriteLine("New connection from " + args.Connection.EndPoint.ToString();
args.Connection.DataReceived += DataReceivedHandler;
args.Recycle();
}
private static void DataReceivedHandler(object sender, DataEventArgs args)
{
Connection connection = (Connection)sender;
Console.WriteLine("Received (" + string.Join<byte>(", ", args.Bytes) + ") from " + connection.EndPoint.ToString());
connection.SendBytes(args.Bytes, args.SendOption);
args.Recycle();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hazel;
using Hazel.Tcp;
namespace HazelExample
{
class ClientExample
{
static Connection connection;
public static void Main(string[] args)
{
NetworkEndPoint endPoint = new NetworkEndPoint("127.0.0.1", 4296);
connection = new TcpConnection(endPoint);
connection.DataReceived += DataReceived;
Console.WriteLine("Connecting!");
connection.Connect();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
connection.Close();
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi I written simple client socket application, where client send some string to server, server receives it and convert the string to upper case and send back to client. Client print the message from server to console. But When I ran the application, I am getting 'input string was not in correct format' error while converting the bytes received from server. Since I am new to C# programming, Can some one help me to understand why this error coming, and how to resolve it?
Server.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server
{
public class ServerSocket
{
private int port;
private Socket serverSocket;
public ServerSocket(int port)
{
this.port = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
/* Associates a Socket with a local endpoint. */
serverSocket.Bind(serverEndPoint);
/*Places a Socket in a listening state.
* The maximum length of the pending connections queue is 100
*/
serverSocket.Listen(100);
}
public void start()
{
Console.WriteLine("Starting the Server");
/* Accept Connection Requests */
Socket accepted = serverSocket.Accept();
/* Get the size of the send buffer of the Socket. */
int bufferSize = accepted.SendBufferSize;
byte[] buffer = new byte[bufferSize];
/* Receives data from a bound Socket into a receive buffer. It return the number of bytes received. */
int bytesRead = accepted.Receive(buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = buffer[i];
}
String receivedData = Encoding.UTF8.GetString(formatted);
Console.WriteLine("Received Data " + receivedData);
String response = receivedData.ToUpper();
byte[] resp = Encoding.UTF8.GetBytes(response);
accepted.Send(resp, 0, resp.Length, 0);
Console.WriteLine("Press some key to close");
Console.Read();
}
}
class Server
{
static void Main(string[] args)
{
ServerSocket server = new ServerSocket(1234);
server.start();
}
}
}
Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace client
{
public class ClientSocket{
private Socket clientSocket;
private int port;
public ClientSocket(int port)
{
this.port = port;
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void start()
{
Console.WriteLine("Starting client socket");
try
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
clientSocket.Connect(serverEndPoint);
Console.WriteLine("Enter some data to send to server");
String data = Console.ReadLine();
byte[] bytes = Encoding.UTF8.GetBytes(data);
clientSocket.Send(bytes);
Console.WriteLine("Closing connection");
int receiveBufferSize = clientSocket.ReceiveBufferSize;
byte[] buffer = new byte[receiveBufferSize];
int receivedBytes = clientSocket.Receive(buffer);
byte[] receivedData = new byte[receivedBytes];
for(int i=0; i < receivedBytes; i++)
{
receivedData[i] = buffer[i];
Console.WriteLine(receivedData[i]);
}
String received = Encoding.UTF8.GetString(receivedData);
Console.WriteLine("Response : {}", received);
Console.WriteLine("Press Enter to close");
Console.Read();
clientSocket.Close();
}
catch (Exception e)
{
Console.WriteLine("Error while connectiong to server {}", e.Message );
}
}
}
class Client
{
static void Main(string[] args)
{
ClientSocket clientSocket = new ClientSocket(1234);
clientSocket.start();
}
}
}
The line:
Console.WriteLine("Response : {}", received);
should be:
Console.WriteLine("Response : {0}", received);
TCP/IP socket program client send text server receive and store database table. I'm righting code below but i have error text reeving time.
This is Client Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.IO;
namespace ClientApplication
{
class Client
{
static void Main(string[] args)
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
//tcpclnt.Connect("162.144.85.232", 8080);
tcpclnt.Connect("162.144.85.232", 4489);
Console.WriteLine("Connected");
Console.Write("Enter the string to be Sent : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
System.Net.ServicePointManager.Expect100Continue = false;
Console.WriteLine("Sending.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
Console.ReadLine();
tcpclnt.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
}
}
}
This Is Server Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ServerApplication
{
class Server
{
static void Main(string[] args)
{
try
{
IPAddress ipadd = IPAddress.Parse("192.168.1.7");
TcpListener list = new TcpListener(ipadd, 8080);
list.Start();
Console.WriteLine("The server is running at port 8080...");
Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
System.Net.ServicePointManager.Expect100Continue = false;
Socket s = list.AcceptSocket();
Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recived...");
for (int i = 0; i < k; i++)
Console.WriteLine(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The String Was Recived throw Server"));
Console.WriteLine("\n Sent Acknowlegment");
s.Close();
list.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
I'm trying to execute this code i have error happen like this
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. Please resolve my issue .
There are a number of problems with the code you posted, but the one directly causing the behavior you're seeing is that the server closes the socket without waiting for the client to finish reading from the connection.
Look up "TCP graceful shutdown" for more information. In the meantime, the following is an improvement on the code you posted and won't have that problem:
Server code:
class Server
{
static void Main(string[] args)
{
try
{
TcpListener list = new TcpListener(IPAddress.Any, 8080);
list.Start();
Console.WriteLine("The server is running at port 8080...");
Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
Socket s = list.AcceptSocket();
Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
byte[] b = new byte[100];
int k;
while ((k = s.Receive(b)) > 0)
{
Console.WriteLine("Recived...");
Console.WriteLine(Encoding.ASCII.GetString(b, 0, k));
s.Send(Encoding.ASCII.GetBytes("The String Was Recived throw Server"));
Console.WriteLine("\n Sent Acknowlegment");
}
s.Shutdown(SocketShutdown.Both);
s.Close();
list.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Client code:
class Client
{
static void Main(string[] args)
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.1.7", 8080);
Console.WriteLine("Connected");
Console.Write("Enter the string to be Sent : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
byte[] ba = Encoding.ASCII.GetBytes(str);
Console.WriteLine("Sending.....");
stm.Write(ba, 0, ba.Length);
tcpclnt.Client.Shutdown(SocketShutdown.Send);
byte[] bb = new byte[100];
int k;
while ((k = stm.Read(bb, 0, 100)) > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(bb, 0, k));
}
Console.ReadLine();
tcpclnt.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
}
}
The key thing here is that both server and client continue to read from the connection until the remote end has, by calling Socket.Shutdown(), signaled that there is no more data to be read.
I also removed the use of the System.Net.ServicePointManager.Expect100Continue property, which had no effect in this code. That only affects programs that use the ServicePoint class and is not useful here.
It's also not clear to me why for the client you use the NetworkStream instead of just getting the Client socket and using it directly. The NetworkStream object is useful when wrapping your I/O in e.g. StreamReader and StreamWriter, but here you're just using Stream.Read() and Stream.Write(), which have the exact same semantics as Socket.Receive() and Socket.Send(), respectively. In any case, note that while you are using the NetworkStream object for the send and receive, you still need to access the underlying Socket instance directly to correctly initiate the graceful shutdown (the endpoint not initiating could just close the NetworkStream, since it doesn't have to shutdown until it's done both sending and receiving).
I also cleaned up the handling of the ASCII-encoded text a bit.
If I don't put a $ symbol at the end of string in the textbox it throws an error saying I have to make a change in the code so that whatever the user puts in the textbox it should be displayed. This is one scenario.
In my second scenario I need to send the number of selected items from the listbox to console.
How do I store selected values in a variable?
This is my client side code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.Net.Sockets;
namespace eg_client
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
string data = textBox2.Text;
byte[] dataB = System.Text.Encoding.Unicode.GetBytes(data);
serverStream.Write(dataB, 0, dataB.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
}
private void Form1_Load_1(object sender, EventArgs e)
{
clientSocket.Connect("127.0.0.1", 8001);
label2.Text = "Client Socket Program - Server Connected ...";
}
}
}
This is my server side code
using System;
using System.Net.Sockets;
using System.Text;
namespace eg_server
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8001);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
Can anyone help me on this?
Your server side code has
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
You have assumed the string will contain one, you need to decide what to do if the string does not have one.. such as
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient.Contains("$"))
{
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
}
else
console.WriteLine("Data received in incorrect format");