Last active
January 9, 2017 20:28
-
-
Save georgepaoli/4e5ea60bc5bb69bc40a7942b8c788731 to your computer and use it in GitHub Desktop.
TCP/IP Socket Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Host | |
{ | |
class Program | |
{ | |
private const int BUFFER_SIZE = 1024; | |
private static Dictionary<string, string> CODIGOS = new Dictionary<string, string>(); | |
static void Main(string[] args) | |
{ | |
// Codigos de Recebimento e Confirmação) | |
CODIGOS.Add("32R", "42R"); | |
CODIGOS.Add("3UE", "4UE"); | |
CODIGOS.Add("3UF", "4UF"); | |
CODIGOS.Add("1UN", "2UN"); | |
if (args.Length > 1) | |
throw new ArgumentException("Parameters: [Port]"); | |
int port = (args.Length == 1) ? Int32.Parse(args[0]) : 9802; | |
Console.Title = "Host - TCP/IP Socket Server - Porta " + port; | |
TcpListener listener = null; | |
try | |
{ | |
listener = new TcpListener(IPAddress.Any, port); | |
listener.Start(); | |
Console.WriteLine("Escutando na porta {0}", port); | |
} | |
catch (SocketException e) | |
{ | |
Console.WriteLine("{0}: {1}", e.ErrorCode, e.Message); | |
Environment.Exit(e.ErrorCode); | |
} | |
var buffer = new byte[BUFFER_SIZE]; | |
while (true) | |
{ | |
TcpClient client = null; | |
NetworkStream stream = null; | |
try | |
{ | |
Console.WriteLine("Aguardando conexão.."); | |
client = listener.AcceptTcpClient(); | |
stream = client.GetStream(); | |
var bytesReceived = 0; | |
Console.WriteLine("Mensagem do cliente:"); | |
var msg = ""; | |
while (true) | |
{ | |
bytesReceived = stream.Read(buffer, 0, BUFFER_SIZE); | |
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesReceived)); | |
msg += Encoding.ASCII.GetString(buffer, 0, bytesReceived); | |
if (bytesReceived != BUFFER_SIZE) break; | |
} | |
Console.WriteLine("Tratando mensagem"); | |
TratarMensagemRecebida(msg, stream); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.ToString()); | |
} | |
finally | |
{ | |
stream.Close(); | |
client.Close(); | |
} | |
} | |
} | |
private static void TratarMensagemRecebida(string msg, NetworkStream stream) | |
{ | |
var START_CHAR = "\n"; //(char)10; | |
var END_CHAR = "\r"; //(char)13 | |
/* Estrutura da msg: | |
* 1 byte - SIMBOLO INICIAL - LF - \n | |
* 5 bytes - BYTECOUNT | |
* 1 a 31995 bytes - DADOS | |
* 1 byte - SIMBOLO FINAL - CR - \r | |
* | |
* Ex msg de entrada: | |
* <LF>|00000|32R|07|06|1234567|123456|C|02|12|D|07|1234567|E|15|123456789012345|G|05|12345|K|......|<CR> | |
* | |
* Ex msg de saida: | |
* <LF>|00012|42R|00|<CR> | |
*/ | |
var codigo = msg.Substring(6, 3); | |
if (CODIGOS.ContainsKey(codigo)) | |
ConfirmarRecebimentoComSucesso(codigo, stream); | |
else | |
ConfirmarRecebimentoComFalha(codigo, stream); | |
// TODO: GRAVAR MSG NO BANCO DE DADOS | |
} | |
private static void ConfirmarRecebimentoComSucesso(string codigo, NetworkStream stream) | |
{ | |
var resp = Encoding.ASCII.GetBytes(string.Format("\n{0}00\r", CODIGOS[codigo])); | |
stream.Write(resp, 0, resp.Length); | |
} | |
private static void ConfirmarRecebimentoComFalha(string codigo, NetworkStream stream) | |
{ | |
// Identificacao do conjunto de dados invalida | |
// Ex.: <LF>|00012|22R|91|<CR> | |
var resp = Encoding.ASCII.GetBytes(string.Format("\n2{0}91\r", codigo.Substring(1, 2))); | |
stream.Write(resp, 0, resp.Length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment