ChatApplication
Chatovací program
C# .NET
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ChatApplication
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epremote;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress,true);
textlocalip.Text = Getlocalip();
textremoteip.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 "";
}
private void buttonconnect_Click(object sender, EventArgs e)
{
epLocal = new IPEndPoint(IPAddress.Parse(textlocalip.Text), Convert.ToInt32(textlocalport.Text));
sck.Bind(epLocal);
epremote = new IPEndPoint(IPAddress.Parse(textremoteip.Text), Convert.ToInt32(textremoteport.Text));
sck.Connect(epremote);
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[] receiveData = new byte[1500];
receiveData = (byte[])aResult.AsyncState;
ASCIIEncoding aEncoding = new ASCIIEncoding();
string receiveMessage = aEncoding.GetString(receiveData);
listmessage.Items.Add("Přítel: " + receiveMessage);
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 buttonsend_Click(object sender, EventArgs e)
{
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendingMessage = new byte[1500];
sendingMessage = aEncoding.GetBytes(textmessage.Text);
sck.Send(sendingMessage);
listmessage.Items.Add("Já: " + textmessage.Text);
textmessage.Text = "";
}
}
}
Neformátovaný
Přidáno: 21.8.2015
Expirace: Neuvedeno