2014年6月28日 星期六

[C#基礎]-TCP/IP Command Line下的簡單範例備份

[C#基礎]-TCP/IP Command Line下的簡單範例備份



 


 


剛才爬文時,發現了一個寫得很好的TCP/IP Command Line下範例,趕緊備份,歡迎有興趣的同好一起來c/p一下。


 


資料來源:http://cs0.wikidot.com/chatbox


 


程式碼如下:


 









using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

class ChatBox
{
int port = 20;

public 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); // create a new thread and then receive message.
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("收到:" + line);
}
}

public void outLoop()
{
while (true)
{
String line = Console.ReadLine();
writer.WriteLine(line);
writer.Flush();
}
}
}



 




沒有留言:

張貼留言