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
| using System.Net;
using System.Net.Sockets;
using DevComponents.DotNetBar.Metro;
namespace _2D_Gamers
{
public partial class Tchat : MetroForm
{
Socket sck;
EndPoint epLocal, epRemote;
byte[] buffer;
public Tchat()
{
InitializeComponent();
}
private void Tchat_Load(object sender, EventArgs e)
{
//Set up socket
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//Get user IP
textIPAmis.Text = GetLocalIP();
textIPVous.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "127.0.0.1";
}
private void connect_Click(object sender, EventArgs e)
{
//Binding Socket
epLocal = new IPEndPoint(IPAddress.Parse(textIPAmis.Text), Convert.ToInt32(textPortAmis.Text));
sck.Bind(epLocal);
//Connecting to remote IP
epRemote = new IPEndPoint(IPAddress.Parse(textIPVous.Text), Convert.ToInt32(textPortVous.Text));
sck.Connect(epRemote);
//Listening the specific port
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
byte[] receivedData = new byte[1500];
receivedData = (byte[])aResult.AsyncState;
//Converting byte[] to string
ASCIIEncoding aEncoding = new ASCIIEncoding();
string receivedMessage = aEncoding.GetString(receivedData);
//Adding this message into listbox
listMessageBox.Items.Add("Friend: " + receivedMessage);
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void envMessage_Click(object sender, EventArgs e)
{
//Convert string message to in byte[]
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendingMessage = new byte[1500];
sendingMessage = aEncoding.GetBytes(textMessage.Text);
//Sending the Encoded message
sck.Send(sendingMessage);
//Adding to the listBox
listMessageBox.Items.Add("Me: " + textMessage.Text);
textMessage.Text = "";
}
}
} |
Partager