Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.IO;
- using System.Threading;
- namespace SweatBand
- {
- class Server
- {
- private static TcpListener listener;
- private const int port = 1337;
- public static void Start()
- {
- listener = new TcpListener(IPAddress.Any, port);
- listener.Start();
- Console.WriteLine("Server started on port " + port);
- ConnectionLoop();
- }
- public static void ConnectionLoop()
- {
- while (true)
- {
- Socket client = listener.AcceptSocket();
- if (!client.Connected) return;
- ASCIIEncoding encoder = new ASCIIEncoding();
- byte[] message = new byte[4096];
- int bytesRead = 0;
- int bytes = client.Receive(message, message.Length, SocketFlags.Peek);
- bytesRead = bytes;
- //message has successfully been received
- string data = Encoding.ASCII.GetString(message, 0, bytesRead);
- Console.WriteLine(data);
- SendToBrowser("hello", ref client);
- client.Close();
- }
- }
- public static void SendToBrowser(String sData, ref Socket mySocket)
- {
- SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);
- }
- public static void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
- {
- int numBytes = 0;
- try
- {
- if (mySocket.Connected)
- {
- if ((numBytes = mySocket.Send(bSendData,
- bSendData.Length, 0)) == -1)
- Console.WriteLine("Socket Error cannot Send Packet");
- else
- {
- Console.WriteLine("No. of bytes send {0}", numBytes);
- }
- }
- else
- Console.WriteLine("Connection Dropped....");
- }
- catch (Exception e)
- {
- Console.WriteLine("Error Occurred : {0} ", e);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment