using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplicationbox
{
class ChatBox
{
int port = 20;
static void Main(string[] args)
{
ChatBox ChatBox = new ChatBox();
if (args.Length == 0) ChatBox.ServerMain();
else
ChatBox.ClientMain(args[0]);
}
public void ServerMain()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Socket client = newsock.Accept();
new TcpListener(client);
newsock.Close();
}
public void ClientMain(String ip)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);
new TcpListener(server);
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}
public class TcpListener
{
Socket socket;
Thread inThread, outTHread;
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
public TcpListener(Socket s)
{
socket = s;
stream= new NetworkStream(s);
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
inThread = new Thread(new ThreadStart(inLoop));
inThread.Start();
outTHread = new Thread(new ThreadStart(outLoop));
outTHread.Start();
inThread.Join(); //等待inThread 執行序完成,才離開此函數
//按照 inLoop的邏輯,這個函數永遠都不會跳出(inLoop 是無窮迴圈)
}
public void inLoop()
{
while(true)
{
String line = reader.ReadLine();
Console.WriteLine("rec: " + line);
}
}
public void outLoop()
{
String line = Console.ReadLine();
writer.WriteLine(line);
writer.Flush();
}
}
}
沒有留言:
張貼留言