Skip to content

Instantly share code, notes, and snippets.

@aoisensi
Created November 10, 2013 03:46
Show Gist options
  • Save aoisensi/7393485 to your computer and use it in GitHub Desktop.
Save aoisensi/7393485 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace TCPChat
{
class Program
{
const string localhost = "localhost";
static readonly Encoding enc = Encoding.Unicode;
static void Main(string[] args)
{
Console.WriteLine("Server or Client? S/C");
char c = Console.ReadLine()[0];
switch (c)
{
case 'C':
case 'c':
Client();
break;
case 'S':
case 's':
Server();
break;
default:
Console.WriteLine("You must die...");
Console.ReadLine();
break;
}
}
static void Server()
{
var ip = Dns.GetHostEntry(localhost).AddressList[0];
Console.WriteLine("Port? 81-65535 Default 52645");
ushort port;
if (!ushort.TryParse(Console.ReadLine(), out port))
port = 52645;
var listner = new TcpListener(ip, port);
listner.Start();
Console.WriteLine("Start Server {0} {1}", ip, port);
var nss = new LinkedList<NetworkStream>();
for (; ; )
{
if (listner.Pending())
{
var client = listner.AcceptTcpClient();
Console.WriteLine("Connected {0}", client);
nss.AddLast(client.GetStream());
}
foreach (var ns in nss)
{
if(!ns.DataAvailable) continue;
var ms = new MemoryStream();
byte[] res = new byte[256];
do
{
int s = ns.Read(res, 0, res.Length);
ms.Write(res, 0, s);
}
while (ns.DataAvailable);
var data = ms.ToArray();
var text = enc.GetString(data, 0, data.Length);
Console.WriteLine(text);
foreach (var cns in nss)
{
if (cns == ns) continue;
cns.Write(data, 0, data.Length);
}
}
}
}
static void Client()
{
Console.WriteLine("HostName?");
var host = Console.ReadLine();
Console.WriteLine("Port? 81-65535 Default 52645");
ushort port;
if (!ushort.TryParse(Console.ReadLine(), out port))
port = 52645;
var client = new TcpClient(host, port);
var ns = client.GetStream();
Thread thread = new Thread(new ThreadStart(new Action(() => {
for (; ; )
{
var data = enc.GetBytes(Console.ReadLine());
ns.Write(data, 0, data.Length);
}
})));
thread.Start();
for (; ; )
{
if (!ns.DataAvailable) continue;
var ms = new MemoryStream();
byte[] res = new byte[256];
do
{
int s = ns.Read(res, 0, res.Length);
ms.Write(res, 0, s);
}
while (ns.DataAvailable);
var data = ms.ToArray();
Console.WriteLine(enc.GetString(data, 0, data.Length));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment