1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Windows.Forms; namespace TestChat { public partial class Form2 : Form { public Form2() { InitializeComponent(); new Server().Go(textBox1); button2.Click += new EventHandler((object sender, EventArgs e) => { button2.Enabled = false; new Client().Go(textBox3,textBox2,button2); }); } } //public class Client //{ // public async void Go(TextBox address, TextBox message, Button button) // { // await Task.Run(()=> { // try // { // using (var tcpClient = new TcpClient(address.Text, 2001)) // { // tcpClient.ReceiveTimeout = 100; // using (NetworkStream networkStream = tcpClient.GetStream()) // { // byte[] buffer = Encoding.UTF8.GetBytes(message.Text); // networkStream.Write(buffer, 0, buffer.Length); // } // } // } // catch(Exception e) // { // MessageBox.Show(e.Message); // } // button.BeginInvoke(new Action(()=> { button.Enabled = true; })); // }); // } //} public class Client { public async void Go(TextBox address, TextBox message, Button button) { using (var tcpClient = new TcpClient()) { await tcpClient.ConnectAsync(address.Text, 2001); using (NetworkStream networkStream = tcpClient.GetStream()) { byte[] buffer = Encoding.UTF8.GetBytes(message.Text); networkStream.Write(buffer, 0, buffer.Length); } } button.Enabled = true; } } public class Server { public async void Go(TextBox textBox) { TcpListener tcpListener = new TcpListener(IPAddress.Any, 2001); tcpListener.Start(); using (var tcpClient = await tcpListener.AcceptTcpClientAsync()) { tcpListener.Stop(); using (NetworkStream networkStream = tcpClient.GetStream()) { byte[] buffer = new byte[1024]; string message = ""; do { int byteSize = networkStream.Read(buffer, 0, buffer.Length); message += Encoding.UTF8.GetString(buffer, 0, byteSize); } while (networkStream.DataAvailable); textBox.Text += message + "\r\n"; } } Go(textBox); } } } |