Rafik El-Kheer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TcpReceiver;
namespace MyServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// private TcpReceiver.Receiver obj;
private Task t;
private void button1_Click(object sender, EventArgs e)
{
var obj = new Receiver();
//Task.Delay(10000).Wait();
// int port = int.Parse(ConfigurationManager.AppSettings["port"]);
t = obj.StartReceiverAsync(1000);
////// StartReceiverAsync(1000);
// TcpListener server = null;
// try
// {
// // Set the TcpListener on port 13000.
// Int32 port = 1000;
// // IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// // TcpListener server = new TcpListener(port);
// server = new TcpListener(IPAddress.Any, port);
// // Start listening for client requests.
// server.Start();
// // Buffer for reading data
// Byte[] bytes = new Byte[1024];
// String data = null;
// // Enter the listening loop.
// while (true)
// {
// Console.Write("Waiting for a connection... ");
// // Perform a blocking call to accept requests.
// // You could also user server.AcceptSocket() here.
// TcpClient client = server.AcceptTcpClient();
// Console.WriteLine("Connected!");
// data = null;
// // Get a stream object for reading and writing
// NetworkStream stream = client.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);
// // Process the data sent by the client.
// data = data.ToUpper();
// // byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// byte[] msg = new byte[] {0x01};
// // Send back a response.
// stream.Write(msg, 0, msg.Length);
// //Console.WriteLine("Sent: {0}", data);
// }
// // Shutdown and end connection
// client.Close();
// }
// }
// catch (SocketException e1)
// {
// Console.WriteLine("SocketException: {0}", e1);
// }
// finally
// {
// // Stop listening for new clients.
// server.Stop();
// }
// Console.WriteLine("\nHit enter to continue...");
// Console.Read();
}
//public async Task<List<Task<bool>>> StartReceiverAsync(int port)
//{
// return await Task.Factory.StartNew(() =>
// {
// // _portToRun = port;
// // use this IP for LAN. for Public IP. We have to choose the Any IP.
// //var selfIp = GetSelfIp();
// bool IsStopRequested = false;
// List<Task<bool>> taskList = new List<Task<bool>>();
// TcpListener listener = new TcpListener(IPAddress.Any, port);
// listener.Start();
// while (!IsStopRequested)
// {
// Socket client = listener.AcceptSocket();
// // taskList.Add(new ProcessClient().ProcessAsync(client));
// }
// return taskList;
// });
//}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using Parser.nsMain.nsInterface;
namespace TcpReceiver
{
public class Receiver
{
public bool IsStopRequested { get; set; }
private int _portToRun;
public async Task<List<Task<bool>>> StartReceiverAsync(int port)
{
return await Task.Factory.StartNew(() =>
{
_portToRun = port;
// use this IP for LAN. for Public IP. We have to choose the Any IP.
//var selfIp = GetSelfIp();
List<Task<bool>> taskList = new List<Task<bool>>();
// IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(IPAddress.Any, _portToRun);
listener.Start();
while (!IsStopRequested)
{
Socket client = listener.AcceptSocket();
taskList.Add(ProcessAsync(client));
}
return taskList;
});
}
internal async Task<bool> ProcessAsync(Socket clientSocket)
{
StreamWriter sr = new StreamWriter("D:\\AVL\\AVL.txt");
bool result = false;
// IMsg msg = null;
return await Task.Factory.StartNew(() =>
{
var ns = new NetworkStream(clientSocket);
byte[] buffer = new byte[1024];
int length;
string total = "";
while ((length = ns.Read(buffer, 0, buffer.Length)) > 0)
{
string msgFromClient = Encoding.Default.GetString(buffer.Take(length).ToArray()).Trim();
byte[] msg = new byte[] { 0x01 };
// Send back a response.
ns.Write(msg, 0, msg.Length);
//if (!string.IsNullOrEmpty(msgFromClient))
//{
// msg = Parser.Parser.ParseTheMsg(msgFromClient);
// list.Enqueue(Tuple.Create(msgFromClient, msg));
// WriteRawData();
// sendmsgtocachethroughUPD(msgFromClient, msg);
//}
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Disconnect(true);
// sr.Close();
return true;
});
}
//private IPAddress GetSelfIp()
//{
// //Task.Delay(10000).Wait();
// string hostname = Dns.GetHostName();
// IPHostEntry entry = Dns.GetHostEntry(hostname);
// var ip = entry.AddressList.First(c => c.AddressFamily == AddressFamily.InterNetwork);
// if (ip == null)
// {
// throw new Exception("No IPv4 address for server");
// }
// return ip;
//}
}
}