Can we create windows service with C# Socket - c#

I want to create a windows service from this code. Anyone can help for creating a windows service. I tried many time myself but i get success 50%. In my code i had 3 function that i want to perform after connecting with client application.
public static class Program
{
public static TcpClient client;
private static TcpListener listener;
private static string ipString;
static void Main(string[] args)
{
IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIp)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
ipString = address.ToString();
}
}
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipString), 1234);
listener = new TcpListener(ep);
listener.Start();
client = listener.AcceptTcpClient();
while (client.Connected)
{
try
{
const int bytesize = 1024 * 1024;
byte[] buffer = new byte[bytesize];
string x = client.GetStream().Read(buffer, 0, bytesize).ToString();
var data = ASCIIEncoding.ASCII.GetString(buffer);
if (data.ToUpper().Contains("SLP2"))
{
Sleep();
}
else if (data.ToUpper().Contains("SHTD3"))
{
Shutdown();
}
else if (data.ToUpper().Contains("TSC1"))
{
var bitmap = SaveScreenshot();
var stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
sendData(stream.ToArray(), client.GetStream());
}
}
catch (Exception exc)
{
client.Dispose();
client.Close();
}
}
}
}

Related

C# Is the TcpListener limited to local area network or is something wrong with my code?

I have a problem with my chat app : it doesn't work over the network . I tried port-forwarding and other similar methods. I'm starting to question my code . I'm new to networking so please help me with this. I heard of another method using System.Net.Sockets but I haven't tried that yet . I heard that Sockets are pretty similar to TcpListener so I don't know what to say about this. I made sure I used the correct IP address , the AddressFamily.InterNetwork. Here is my code :
static TcpListener server;
public static void ListenThread()
{
TcpClient client = null;
NetworkStream stream = null;
ClientConnection currentClientConnection = new ClientConnection();
while (true)
{
if(client == null)
{
client = server.AcceptTcpClient();
stream = client.GetStream();
currentClientConnection = new ClientConnection(client, stream);
clients.Add(currentClientConnection);
currentConnections++;
// Logging
string text = "A Client connection establieshed ! Connections : " + currentConnections;
Console.WriteLine(text);
Logger.WriteToLog(text);
}
int bufferSize = client.ReceiveBufferSize;
byte[] buffer = new byte[bufferSize];
int i;
string data = null;
try
{
while ((i = stream.Read(buffer, 0, bufferSize)) != 0)
{
data = Encoding.ASCII.GetString(buffer, 0, i);
data = ProcessData(data);
if (data == "/disconnect")
{
clients.Remove(currentClientConnection);
currentConnections--;
// Logging
string text = "A user left the server ! Connections : " + currentConnections;
Console.WriteLine(text);
Logger.WriteToLog(text);
SendToAllClients(string.Format("[Server]>> A user left the chat!"), client);
client.Close();
stream.Close();
client = null;
break;
}
else
{
SendToAllClients(data, client);
}
}
}
catch { };
}
}
static void InitialiseServer()
{
Console.Write("Enter a port : ");
serverPort = int.Parse(Console.ReadLine());
Console.WriteLine();
IPAddress localMachineIP = GetLocalIPAddress();
try
{
Console.WriteLine("Initialising Server...");
server = new TcpListener(localMachineIP,serverPort);
Console.WriteLine("Server initialised !");
}
catch(Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
string text = string.Format("An error has occured while initalising server under IP={0} and port={1} . {2}", localMachineIP, serverPort, e.Message);
Console.WriteLine(text);
Logger.WriteToLog(text);
Console.ForegroundColor = baseColor;
}
Console.Title = string.Format("Server initailised under {0}:{1}",localMachineIP.ToString(),serverPort);
}
public static IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
return null;
}

Connecting two PCs through TCP using C#

I'm trying to establish a TCP connection between two PCs (mine & friend's). Now, I know that the logic is very simple but I want to check if the connection is successful.
The friend of mine starts the server and gives me the IP address via whatismyip.com, but when I enter that IP I get the timeout error.
I'm not quite sure that this is the right way of establishing the connection to PC in another LAN. Will be glad for any help \ advises \ external links.
Below is my code:
internal class Server
{
private TcpListener m_server;
private readonly int m_port = 8888;
public void Start()
{
try
{
m_server = new TcpListener(IPAddress.Any, m_port);
m_server.Start();
Console.WriteLine("Server started");
while(true)
{
TcpClient client = m_server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
int bytes = stream.Read(data, 0, data.Length);
string message = Encoding.UTF8.GetString(data, 0, bytes);
Console.WriteLine("From client: " + message);
stream.Close();
client.Close();
if (message == "Shutdown")
{
m_server.Stop();
}
}
}
catch(Exception e)
{
Console.WriteLine("Server: " + e.Message);
}
finally
{
m_server?.Stop();
}
}
}
internal class Client
{
private System.Net.Sockets.TcpClient m_client;
private readonly string m_ip = "";
private readonly int m_port = 8888;
private readonly string m_message = "Shutdown1";
public void Start()
{
try
{
m_client = new System.Net.Sockets.TcpClient();
m_client.Connect(m_ip, m_port);
NetworkStream stream = m_client.GetStream();
byte[] data = Encoding.UTF8.GetBytes(m_message);
stream.Write(data, 0, data.Length);
stream.Close();
m_client.Close();
Console.WriteLine("Done");
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
}
}

TCP/IP listener variable byte length

I have a stream coming in that varies in length but has a start and stop character. When I run this code:
public TCPListener()
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
// Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
// Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
private void HandleClient(object tcpClient)
{
// string path = #"c:\Test.txt";
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[135];
String data = null;
int i;
try
{
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
URLObject oU = new URLObject();
oU = oDecode.TextFrameDecode(data);
Console.WriteLine(data);
Console.WriteLine("");
}
}
catch (Exception ex)
{ }
// Console.WriteLine(data);
}
I get a lot of data every second; I get the data, but it's broken up sometimes into chunks that are not parsable. When I run this code to look for the end delimiter, the feed only get one connection every couple of minutes with only one record so I think the data is getting truncated which is not correct.
static void Main(string[] args)
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
static void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[135];
String data = null;
int i;
try
{
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
{
string inputLine = reader.ReadLineSingleBreak();
inputLine = inputLine + "#";
Console.WriteLine(inputLine);
URLObject oU = new URLObject();
oU = oDecode.TextFrameDecode(inputLine);
}
}
catch (Exception ex)
{ }
}
}
public static class StreamReaderExtensions
{
public static string ReadLineSingleBreak(this StreamReader self)
{
StringBuilder currentLine = new StringBuilder();
int i;
char c;
while ((i = self.Read()) >= 0)
{
c = (char)i;
if (c == '#')
{
break;
}
currentLine.Append(c);
}
return currentLine.ToString();
}
}
I need a mix of both... get all the data but then parse it correctly.
I did fix it by Pieter Witvoet advice:
static private TcpListener server = null;
static private Decode oDecode = new Decode();
static private string sLeftOver = string.Empty;
static void Main(string[] args)
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
static void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[256];
String data = null;
int i;
try
{
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
URLObject oU = new URLObject();
Console.WriteLine(data);
Console.WriteLine("");
//Split data here
string[] aData = Regex.Split(data, #"(?<=[#])");
foreach (string s in aData)
{
string sData = s;
sData = sLeftOver + sData;
if (sData.EndsWith("#"))
{
sLeftOver = string.Empty;
Console.WriteLine(sData);
Console.WriteLine("");
oU = oDecode.TextFrameDecode(sData);
}
else
{
sLeftOver = s;
}
}
}
}
catch (Exception ex)
{ }
}

Socket Programming [Socket and Server]

I am trying to make a message server and I have an error with this code:
The error "is only one use of each socket address can be normally permitted"
Server:
class Program
{
//Server Control
static bool stop = false;
static bool pause_listening = false;
//Server Info
static int port = 11000;
static string server_ip = null;
//User Declaration
static List<user> allUsers = new List<user>();
static int users = 0;
//IP Address
static IPAddress ipaddr;
static IPEndPoint localEP;
static IPEndPoint userportEP;
static IPEndPoint temp;
//Data
static string data = null;
static byte[] bytes = new Byte[1024];
//Threads
static Thread listener = new Thread(listen);
static Thread server_control = new Thread(Options);
static Thread UserPort = new Thread(addUserPort);
static void Main(string[] args)
{
Console.WriteLine("Message Server");
start();
}
static void start()
{
server_ip = input("What is your local IPv4 address");
ipaddr = IPAddress.Parse(server_ip);
allUsers.Add(new user());
allUsers[users].name = "Admin";
allUsers[users].ip = server_ip;
allUsers[users].desc = "Nimda";
allUsers[users].id = 0;
localEP = new IPEndPoint(ipaddr, port);
userportEP = new IPEndPoint(ipaddr, 1300);
UserPort.Start();
listener.Start();
server_control.Start();
}
static void addUserPort()
{
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(userportEP);
listener.Listen(10);
Console.WriteLine("User Listener Started");
// Start listening for connections.
while (pause_listening || stop != true)
{
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string value = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
Console.WriteLine("Someone Requested");
if(value.IndexOf( "!au") > -1)
{
String[] rawData = value.Split('|');
String[] userData = new String[3];
for(int x = 0; x < rawData.Length; x++)
{
String stringbuff = rawData[x];
if(stringbuff.IndexOf("name:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[0];
}
else if (stringbuff.IndexOf("ipaddr:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[1];
}
else if (stringbuff.IndexOf("desc:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[2];
}
}
addUser(userData[0], userData[1], userData[2]);
}
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void listen()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Message Listener Started");
try
{
listener.Bind(localEP);
listener.Listen(10);
while (pause_listening || stop != true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 && data.IndexOf("<!META>") > -1)
{
textSent(data);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void addUser(String name, String ip, String desc)
{
users++;
allUsers.Add(new user());
userportEP = new IPEndPoint(IPAddress.Parse(ip), 1300);
allUsers[users].name = name;
allUsers[users].ip = ip;
allUsers[users].desc = desc;
allUsers[users].id = users;
byte[] msg = Encoding.ASCII.GetBytes(string.Format("!Join<!PORT>{0}<!PORT><!EOM>", port));
Socket confirm = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
confirm.Bind(userportEP);
confirm.Connect(userportEP);
confirm.Send(msg);
confirm.Shutdown(SocketShutdown.Both);
confirm.Close();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void Options()
{
while(stop == false)
{
Console.Write("\n Server>>");
String command = Console.ReadLine();
switch (command)
{
case "stop":
stop = true;
listener.Abort();
UserPort.Abort();
StopServer();
break;
default:
Console.WriteLine("\t The command \"{0} \" is not valid", command);
break;
}
}
}
static void StopServer()
{
Console.WriteLine("Server is stopping");
Console.Read();
}
static void textSent(String text)
{
String[] rawText = text.Split(new string[] { "<!META>" }, StringSplitOptions.None) ;
String message = rawText[0];
String[] meta = rawText[1].Split(':');
String package = meta[0] + ": " + message + "<!EOM>";
SendToAll(package);
}
static void SendToAll(String pack)
{
byte[] msg = Encoding.ASCII.GetBytes(pack);
Socket send_socket= new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
for (int x = 0; allUsers.Count < x; x++)
{
temp = new IPEndPoint(IPAddress.Parse(allUsers[x].ip), port);
send_socket.Bind(temp);
send_socket.Connect(temp);
send_socket.Send(msg);
}
send_socket.Shutdown(SocketShutdown.Both);
send_socket.Close();
}
}
Client:
class Program
{
static int port;
static string server_ip;
static string ign;
static string desc;
static string ip;
static bool connected = false;
static bool exit = false;
static IPEndPoint remoteEP;
static IPEndPoint remoteUserRequestEP;
static IPEndPoint localEP;
static IPEndPoint userRequestListen;
static Socket listen;
static Socket send;
static Thread listenThread;
static Thread sendThread;
static void Main(string[] args)
{
Console.WriteLine("Message Client");
start();
}
static void start()
{
server_ip = input("Please Enter your Server I.P.");
remoteUserRequestEP = new IPEndPoint(IPAddress.Parse(server_ip), 1300);
ip = input("Enter your local IPv4 Address");
desc = input("Enter a short description");
ign = input("Enter a name to represent yourself");
localEP = new IPEndPoint(IPAddress.Parse(ip), 11000);
userRequestListen = new IPEndPoint(IPAddress.Parse(ip), 1300);
listenThread = new Thread(listening);
sendThread = new Thread(createSend);
listenThread.Start();
sendThread.Start();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void listening()
{
listen = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
String data;
byte[] bytes;
try
{
listen.Bind(localEP);
listen.Listen(1);
while (exit == false)
{
Socket handler = listen.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 )
{
string finalMSG = data.Replace("<!EOM>", null);
Console.WriteLine(finalMSG);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void requestAcesss()
{
byte[] msg = new byte[1024];
msg = Encoding.ASCII.GetBytes(string.Format("!au|name:{0}|ipaddr:{1}|desc:{2}|<!EOM>", ign, ip, desc));
Socket usrRequest = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
usrRequest.Bind(userRequestListen);
usrRequest.Connect(userRequestListen);
usrRequest.Send(msg);
try {
while (connected == false)
{
Socket handler = usrRequest.Accept();
string value = null;
while (true)
{
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
String[] raw = value.Split(new string[] { "<!PORT>" }, StringSplitOptions.None);
port = Int32.Parse(raw[1]);
remoteEP = new IPEndPoint(IPAddress.Parse(server_ip), port);
localEP = new IPEndPoint(IPAddress.Parse(ip), port);
Console.WriteLine(port);
connected = true;
startServices();
}
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void createSend()
{
byte[] msg = new byte[1024];
send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while(exit == false)
{
string raw = Console.ReadLine();
if (raw == "exit")
{
exit = true;
listenThread.Abort();
sendThread.Abort();
stop();
break;
}
string finalmsg = string.Format( raw + "<!META>name:{0}<!META><!EOM>", ign);
send.Bind(localEP);
msg = Encoding.ASCII.GetBytes(finalmsg);
send.Send(msg);
}
send.Shutdown(SocketShutdown.Both);
send.Close();
}
static void startServices()
{
listenThread.Start();
sendThread.Start();
}
static void stop()
{
Console.WriteLine("Press any key to terminate");
Console.ReadLine();
}
}
The sockets aren't used twice nor does a thread get started twice.
Having the same error, I came looking for an answer. Finally found it myself:
An earlier instance of the process may still be running, if you didn't stop it well, e.g. using just Ctrl+C.

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