C# server and client not working - c#

I have been making a C# server and client for a game. I have used many resources to try to create something successful. So far, the client can send stuff to the server and the server can receive them, but I want to be able to send stuff to the client. Also, I don't know what happened, but my server code suddenly stopped printing to console or something. I am new at this and any help is needed. I think I programmed both client and server to be able to send and receive, but something isn't right...
Note: I am using a cmd compiler running an old version of the .NET (but the code still compiles), any help on getting visual studio working to build/compile the code would also be nice :)
Client-side:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
static Boolean done = false;
static void Main(string[] args)
{
Boolean exception_thrown = false;
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse("ip-goes-here");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 27020);
Console.WriteLine("Enter text to broadcast via UDP.");
Console.WriteLine("Enter a blank line to exit the program.");
Thread listenerT = new Thread(new ThreadStart(Program.listener));
listenerT.Start();
while (!done)
{
Console.WriteLine("Enter text to send, blank line to quit");
string text_to_send = Console.ReadLine();
if (text_to_send.Length == 0)
{
done = true;
listenerT.Abort();
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("sending to address: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
try
{
sending_socket.SendTo(send_buffer, sending_end_point);
}
catch (Exception send_exception)
{
exception_thrown = true;
Console.WriteLine(" Exception {0}", send_exception.Message);
}
if (exception_thrown == false)
{
Console.WriteLine("Message has been sent to the broadcast address");
}
else
{
exception_thrown = false;
Console.WriteLine("The exception indicates the message was not sent.");
}
}
}
}
static void listener()
{
int listenPort = 27020;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string received_data;
byte[] receive_byte_array;
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
receive_byte_array = listener.Receive(ref groupEP);
Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
Console.WriteLine("data follows \n{0}\n\n", received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Server side:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class UDPListener
{
private const int listenPort = 27020;
//static Boolean done = false;
static IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
static UdpClient udpServer = new UdpClient(27020);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 27020);
static byte[] data = udpServer.Receive(ref remoteEP); // listen on port 11000
static IPAddress send_to_address = IPAddress.Parse("10.240.0.1");
static IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 27020);
public static void Main()
{
Console.WriteLine("Begin listening sequence");
while (true)
{
data = udpServer.Receive(ref groupEP);
Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
send_to_address = IPAddress.Parse(groupEP.ToString());
Thread listenerT = new Thread(new ThreadStart(UDPListener.sender));
listenerT.Start();
String received_data = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine(received_data);
}
}
static void sender()
{
while (true)
{
Console.WriteLine("Enter text to send, blank line to quit");
string text_to_send = Console.ReadLine();
if (text_to_send.Length == 0)
{
//done = true;
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("sending to address: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
udpServer.Send(send_buffer, 0, remoteEP); // reply back
}
}
}
}

Nevermind, a friend of mine figured it out. You can find the final code in a github repo called something like flaming leaf server

Related

Adding Security To Chat Client

So this is my basic chat program which allows user to add its own IP and receive an IP, plus custom ports to communicate.
In the windows forms design I have:
Textbox --- textLocalIp
Textbox --- textLocalPort
Textbox --- textFriendIp
Textbox --- textFriendPort
Textbox --- textMessage
Listbox --- listMessage
Button --- Start
Button --- Send
So this is a very basic client but what I want help with is making it secure/more secure because security right now is not good.
Maybe like a tunnel with different IP's so that you don't have to know the receivers IP, just a IP they provide which then sends it to them or whatever?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Client
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendIp.Text = GetLocalIP();
}
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[] recievedData = new byte[1464];
recievedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(recievedData);
listMessage.Items.Add("Sender: "+receivedMessage);
}
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 button1_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
sck.Send(msg);
listMessage.Items.Add("Local:" + textMessage.Text);
textMessage.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void start_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(textFriendIp.Text), Convert.ToInt32(textFriendPort.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
start.Text = "Connected";
start.Enabled = false;
send.Enabled = true;
textMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
It is more difficult to implement socket communication security using channels. So I suggest you encrypt the IP and transmission content.
For IP encryption, you can set the Passwordchar attribute of the TextBox to *.
For transmission content, you can encrypt it with an encryption algorithm.
The following code implements the communication between a server and multiple clients, and you can perform encryption on this basis.
Server:
namespace Server
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885;
static Socket serverSocket;
static void Main(string[] args)
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, myProt));
serverSocket.Listen(10); //Set up to 10 queued connection requests
Console.WriteLine("Start listening {0} successfully", serverSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// Listen for Client connections
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// receive data
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Client:
namespace Client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885));
Console.WriteLine("Successfully connected to the server");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press Enter to exit!");
return;
}
//Receive data through clientSocket
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("Server:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
//Send data through clientSocket
for (int i = 0; i <3; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Client:{0}" + sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("After sending, press Enter to exit");
Console.ReadLine();
}
}
}

C# Sockets (TCP & UDP)

I'll cut to the point, I've been stuck on this for a few hours now. Tons of Google and tons of research but not straight answer as of yet.
I have a client and a server coded for TCP which functions perfectly fine, however, I want the client to also be able to use UDP with the server for none-important packets such as player location.
As of right now, this is my connect code for connected clients.
public void ConnectToServer(){
tcp_client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
tcp_client.Connect(server_ip, server_port);
tcp_stream = new NetworkStream(this.tcp_client);
this.udp_client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.udp_client.BeginConnect(IPAddress.Parse(server_ip), server_port,new AsyncCallback(udp_connected), null);
}
Now the client isn't what I've had issues with for when I use udp.Send(byteArray) it appears to be sending as it's not throwing any exceptions but the server itself isn't responding to any data received.
Please Note this is NOT 100% copy/pasted code. Alter to show just what's being an issue.
private Socket c;
private UdpClient udp;
private isRunning = true;
public Client(Socket c){
// This was accepted from TcpListener on Main Server Thread.
this.c = c;
this.networkStream = new NetworkStream(this.c);
udp = new UdpClient();
udp.Connect((IPEndPoint)c.RemoteEndPoint);
// Then starts 2 thread for listening, 1 for TCP and 1 for UDP.
}
private void handleUDPTraffic(){
IPEndPoint groupEP = (IPEndPoint)c.RemoteEndPoint;
while (isRunning){
try{
byte[] udp_received = udp.Receive(ref groupEP);
Console.WriteLine("Received UDP Packet Data: " + udp_received.Length);
}catch{
log.ERROR("UDP", "Couldn't Receive Data...");
}
}
}
You can use both TCP and UDP on the same port. See also:
Can TCP and UDP sockets use the same port?
The sample below demonstrates that, you can simultaneously send and receive UDP and TCP messages.
Maybe, your UdpClient creation to listen for incoming datagrams is the problem. I recommend to create it once like your TcpListener.
The servers:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TCPUDPServer
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpServer = null;
UdpClient udpServer = null;
int port = 59567;
Console.WriteLine(string.Format("Starting TCP and UDP servers on port {0}...", port));
try
{
udpServer = new UdpClient(port);
tcpServer = new TcpListener(IPAddress.Any, port);
var udpThread = new Thread(new ParameterizedThreadStart(UDPServerProc));
udpThread.IsBackground = true;
udpThread.Name = "UDP server thread";
udpThread.Start(udpServer);
var tcpThread = new Thread(new ParameterizedThreadStart(TCPServerProc));
tcpThread.IsBackground = true;
tcpThread.Name = "TCP server thread";
tcpThread.Start(tcpServer);
Console.WriteLine("Press <ENTER> to stop the servers.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Main exception: " + ex);
}
finally
{
if (udpServer != null)
udpServer.Close();
if (tcpServer != null)
tcpServer.Stop();
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
}
private static void UDPServerProc(object arg)
{
Console.WriteLine("UDP server thread started");
try
{
UdpClient server = (UdpClient)arg;
IPEndPoint remoteEP;
byte[] buffer;
for(;;)
{
remoteEP = null;
buffer = server.Receive(ref remoteEP);
if (buffer != null && buffer.Length > 0)
{
Console.WriteLine("UDP: " + Encoding.ASCII.GetString(buffer));
}
}
}
catch (SocketException ex)
{
if(ex.ErrorCode != 10004) // unexpected
Console.WriteLine("UDPServerProc exception: " + ex);
}
catch (Exception ex)
{
Console.WriteLine("UDPServerProc exception: " + ex);
}
Console.WriteLine("UDP server thread finished");
}
private static void TCPServerProc(object arg)
{
Console.WriteLine("TCP server thread started");
try
{
TcpListener server = (TcpListener)arg;
byte[] buffer = new byte[2048];
int count;
server.Start();
for(;;)
{
TcpClient client = server.AcceptTcpClient();
using (var stream = client.GetStream())
{
while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
{
Console.WriteLine("TCP: " + Encoding.ASCII.GetString(buffer, 0, count));
}
}
client.Close();
}
}
catch (SocketException ex)
{
if (ex.ErrorCode != 10004) // unexpected
Console.WriteLine("TCPServerProc exception: " + ex);
}
catch (Exception ex)
{
Console.WriteLine("TCPServerProc exception: " + ex);
}
Console.WriteLine("TCP server thread finished");
}
}
}
The clients:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TCPUDPClient
{
class Program
{
static void Main(string[] args)
{
UdpClient udpClient = null;
TcpClient tcpClient = null;
NetworkStream tcpStream = null;
int port = 59567;
ConsoleKeyInfo key;
bool run = true;
byte[] buffer;
Console.WriteLine(string.Format("Starting TCP and UDP clients on port {0}...", port));
try
{
udpClient = new UdpClient();
udpClient.Connect(IPAddress.Loopback, port);
tcpClient = new TcpClient();
tcpClient.Connect(IPAddress.Loopback, port);
while(run)
{
Console.WriteLine("Press 'T' for TCP sending, 'U' for UDP sending or 'X' to exit.");
key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.X:
run = false;
break;
case ConsoleKey.U:
buffer = Encoding.ASCII.GetBytes(DateTime.Now.ToString("HH:mm:ss.fff"));
udpClient.Send(buffer, buffer.Length);
break;
case ConsoleKey.T:
buffer = Encoding.ASCII.GetBytes(DateTime.Now.ToString("HH:mm:ss.fff"));
if (tcpStream == null)
tcpStream = tcpClient.GetStream();
tcpStream.Write(buffer, 0, buffer.Length);
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Main exception: " + ex);
}
finally
{
if(udpClient != null)
udpClient.Close();
if(tcpStream != null)
tcpStream.Close();
if(tcpClient != null)
tcpClient.Close();
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
}
}
}

C# How to do to send more message to Server with Client?

Im writing a Client Server Socket C# with TCP protocoll to create sort of "Client Ask, Server Answer" But when I Execute first command my client close. I should put while somewhere but I don't know where. here is the code:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
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());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Now If you copy paste this code and execute Server and then Client, you can write something into CLient prompt and get an answers but at 2 attempt CLient close because there is no while that continues the process! I tried put while out of try and into but code crashed! An Help would be appreciate an help or solution is the same, just get an answer :)
Thank you everyone
I have limited knowledge working with sockets. However I know you should only call the following once:
Socket handler = listener.Accept();
I added a while loop under the above line and also removed your break statements at the end of your if conditions.
So the new code becomes:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
while (true)
{
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
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());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
while (true)
{
try
{
//if (!listener.IsBound)
//{
listener.Bind(localEndPoint);
//}
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
while (true)
{
data = null;
// An incoming connection needs to be processed.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
//break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
//break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
//break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}

How to send a message from client to server using c# containg spaces

I create the following code but there is one problem: I can't sent a large message from client to server which contains spaces.
Here is my code for server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ServerApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting: Creating Socket object");
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for connection on port 2112");
Socket socket = listener.Accept();
string receivedValue = string.Empty;
while (true)
{
if (socket.Available > 0)
{
byte[] receivedBytes = new byte[socket.ReceiveBufferSize];
int numBytes = socket.Receive(receivedBytes);
Console.WriteLine("Receiving...");
receivedValue += Encoding.ASCII.GetString(receivedBytes);
break;
}
}
Console.WriteLine("Received value: {0}", receivedValue);
Console.WriteLine("Enter ur Msg");
string replyValue = Console.ReadLine();
//string replyValue = "Message successfully received.";
byte[] replyMessage = Encoding.ASCII.GetBytes(replyValue);
socket.Send(replyMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
listener.Close();
}
}
}
And here is my code for client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ClientApp
{
class Program
{
static void Main(string[] args)
{
byte[] receivedBytes = new byte[2048];
//IPHostEntry ipHost = Dns.Resolve("192.168.1.55");
IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
IPAddress ipAddress = ipHost.AddressList[0];
//IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8000);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2112);
Console.WriteLine("Starting: Creating Socket object");
Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Successfully connected to {0}",sender.RemoteEndPoint);
Console.WriteLine("Enter Client Message :");
string sendingMessage = Console.ReadLine();
//string sendingMessage = "Hello World Socket Test";
Console.WriteLine("Creating message:{0}",sendingMessage);
byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
sender.Send(forwardMessage);
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}",Encoding.ASCII.GetString(receivedBytes,0, totalBytesReceived));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
}
}
}
Please tell me the right way to do this.
Thanks in advance for you suggestions
Server
Console.WriteLine("Starting: Creating Socket object");
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for connection on port 2112");
Socket socket = listener.Accept();
string receivedValue = string.Empty;
while (true)
{
if (socket.Available > 0)
{
do
{
var receivedBytes = new byte[socket.Available];
socket.Receive(receivedBytes);
Console.WriteLine("Receiving...");
receivedValue += Encoding.Default.GetString(receivedBytes);
} while (socket.Available > 0);
break;
}
}
Console.WriteLine("Received value: {0}", receivedValue);
Console.WriteLine("Enter ur Msg");
string replyValue = Console.ReadLine();
//string replyValue = "Message successfully received.";
byte[] replyMessage = Encoding.Default.GetBytes(replyValue);
socket.Send(replyMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
listener.Close();
Client
byte[] receivedBytes = new byte[2048];
//IPHostEntry ipHost = Dns.Resolve("192.168.1.55");
IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
IPAddress ipAddress = ipHost.AddressList[0];
//IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8000);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2112);
Console.WriteLine("Starting: Creating Socket object");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Successfully connected to {0}", sender.RemoteEndPoint);
Console.WriteLine("Enter Client Message :");
string sendingMessage = Console.ReadLine();
//string sendingMessage = "Hello World Socket Test";
Console.WriteLine("Creating message:{0}", sendingMessage);
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
sender.Send(forwardMessage);
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receivedBytes, 0, totalBytesReceived));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();

Issue with passing a variable C#

I am working on a project where I am going to create a TCP/IP Chat application and I have some problems with passing variables between the classes. The variable data does not get passed on from the handleClient to the main class where data along with clientSocket is saved to a Hashtable. The Hashtable is later going to be used for broadcasting the message to all clients. The error i get is as follows: "Error: The name 'data' does not exist in the current context"
Serverside code:
using System;
using System.IO;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections;
namespace Chat_server
{
public class Program
{
//Creates a list with all clients
public static Hashtable clientList = new Hashtable();
public void Main(string[] args)
{
TcpListener serverSocket = null;
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
serverSocket = new TcpListener(localAddr, port);
// Start listening for client requests.
serverSocket.Start();
int counter = 0;
while (true)
{
counter += 1;
Console.WriteLine("Waiting for a connection... ");
TcpClient clientSocket = serverSocket.AcceptTcpClient();
clientList.Add(data, clientSocket);
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClient hclient = new handleClient();
hclient.startClient(clientSocket);
}
}
}
}
//Class to handle each connection separatly
public class handleClient
{
TcpClient clientSocket;
Hashtable clientList;
public void startClient(TcpClient inClient)
{
this.clientSocket = inClient;
Thread clientThread = new Thread(new ThreadStart(doChat));
clientThread.Start();
}
public void doChat()
{
Byte[] bytes = new Byte[10025];
String data = null;
data = null;
while ((true))
{
try
{
foreach (DictionaryEntry Item in clientList)
{
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clientSocket.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
stream.Flush();
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
clientSocket.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
}
}
}
}
data isn't defined in that function or in the class at:
clientList.Add(data, clientSocket);

Categories

Resources