UDPを使ったテストプログラム。
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 |
using System; using System.Text; using System.Linq; using System.Collections.Generic; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace TestChat { public partial class Form1 : Form { public Form1() { InitializeComponent(); StartReceive(); button1.Click += new EventHandler(SendMessage); } public class UdpState { public UdpClient UdpClient; public IPEndPoint IPEndPoint; public UdpState(UdpClient udpClient, IPEndPoint endPoint) { UdpClient = udpClient; IPEndPoint = endPoint; } } public class Message { private List<string> TextList = new List<string>(); private static Message Instance = null; public static Message GetInstance() { if(Instance == null) { Instance = new Message(); } return Instance; } public void SetMessage(string text) { TextList.Add(text); } public string GetMessage() { return string.Join("\r\n", TextList.ToArray().Reverse()); } } private void StartReceive() { IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 2002); UdpClient udpClient = new UdpClient(endPoint); udpClient.BeginReceive(ReceiveCallback, new UdpState(udpClient, endPoint)); } private void ReceiveCallback(IAsyncResult ar) { UdpClient udpClient = ((UdpState)ar.AsyncState).UdpClient; IPEndPoint endPoint = ((UdpState)ar.AsyncState).IPEndPoint; byte[] receiveByte = udpClient.EndReceive(ar,ref endPoint); string receiveString = Encoding.UTF8.GetString(receiveByte); textBox1.BeginInvoke(new Action<string>(ShowReceive), receiveString); udpClient.BeginReceive(ReceiveCallback, new UdpState(udpClient, endPoint)); } private void ShowReceive(string s) { Message message = Message.GetInstance(); message.SetMessage(s); textBox1.Text = message.GetMessage(); } private async void SendMessage(object sender, EventArgs e) { UdpClient udpClient = new UdpClient(); udpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.11.18"), 2002)); byte[] sendByte = Encoding.UTF8.GetBytes(textBox2.Text); await udpClient.SendAsync(sendByte, sendByte.Length); udpClient.Close(); } } } |