Net Client
手動でネットワーク通信するものを作ってみた。前の日記に書いたSMTP in C#をダウングレードさせて作ってみた。SMTP in C#のほうは添付ファイルとかもつけられるようになった。気が向いたら、ここに書くかもしれない。GUIもできたら作ろうか。
ソースは続きへ
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.IO; using System.Threading; namespace NetClient { class Program { static TcpClient Client; static NetworkStream NStream; static Thread reader; static Thread writer; static bool reading = true; static string server; static int port = -1; static void Set() { Console.Write("ServerAddress?\r\n>"); server = Console.ReadLine(); do { Console.Write("Port?\r\n>"); try { port = int.Parse(Console.ReadLine()); } catch { Console.WriteLine("Type Port Number"); } } while (port < 1); } static bool SetClient() { try { Client = new TcpClient(server, port); } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } return true; } static void Main(string[] args) { do { Set(); } while (!SetClient()); NStream = Client.GetStream(); reader = new Thread(new ThreadStart(read)); writer = new Thread(new ThreadStart(write)); reader.Start(); writer.Start(); } static void read() { while (true) { int read; reading = false; try { read = NStream.ReadByte(); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } if (read == -1) { Thread.Sleep(500); } else { reading = true; Console.Write( (char)read ); } } } static void write() { while (true) { Thread.Sleep(500); if (!reading) { Console.Write(">"); string read_string = Console.ReadLine(); byte[] read_byte = Encoding.UTF8.GetBytes(read_string); try { NStream.Write(read_byte, 0, read_byte.Length); NStream.Write(new byte[] { 13, 10 }, 0, 2); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } } } } } }