/gist:ea4b5a974fc6f9aa2bb6 Secret
Created
July 31, 2014 08:02
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Data; | |
using System.Windows.Documents; | |
using System.Windows.Input; | |
using System.Windows.Media; | |
using System.Windows.Media.Imaging; | |
using System.Windows.Shapes; | |
using System.Net.Sockets; | |
using System.Net; | |
using System.Diagnostics; | |
using System.Threading; | |
using System.Net.NetworkInformation; | |
namespace CScharpChat | |
{ | |
/// <summary> | |
/// Interaktionslogik für Chat_window.xaml | |
/// </summary> | |
public partial class Chat_window : Window | |
{ | |
string name = "testuser"; | |
IPAddress Add; | |
private static ManualResetEvent connectDone = new ManualResetEvent(false); | |
private static ManualResetEvent sendDone = new ManualResetEvent(false); | |
private static ManualResetEvent receiveDone = new ManualResetEvent(false); | |
private static string response = String.Empty; | |
static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
static Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
int clientPort; | |
int serverPort = 50000; | |
public Chat_window() | |
{ | |
fileWriter("Chat started",false); | |
InitializeComponent(); | |
starteServer(); | |
} | |
public void set_name(string val) | |
{ | |
name = val; | |
} | |
private void tb_ipadresse_GotFocus(object sender, RoutedEventArgs e) | |
{ | |
tb_ipadresse.Text = ""; | |
} | |
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e) | |
{ | |
tb_eingabe.Text = ""; | |
} | |
private void btn_connect_Click(object sender, RoutedEventArgs e) | |
{ | |
connectbtn(); | |
tb_ipadresse.IsEnabled = false; | |
} | |
private void btn_submit_Click(object sender, RoutedEventArgs e) | |
{ | |
submit_message(); | |
} | |
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e) | |
{ | |
if (e.Key == Key.Return) | |
{ | |
submit_message(); | |
} | |
} | |
private void tb_ipadresse_KeyDown(object sender, KeyEventArgs e) | |
{ | |
if (e.Key == Key.Return) | |
{ | |
connectbtn(); | |
} | |
} | |
private void tb_ipadresse_TextChanged(object sender, TextChangedEventArgs e) | |
{ | |
if (tb_ipadresse.Text.Split('.').Length.Equals(4) || tb_ipadresse.Text.Split(':').Length.Equals(2)) // hier wird auf eine valide Ip geprueft | |
{ | |
if (IPAddress.TryParse(tb_ipadresse.Text, out Add)) | |
{ | |
btn_connect.IsEnabled = true; | |
} | |
else | |
{ | |
btn_connect.IsEnabled = false; | |
} | |
} | |
} | |
private void btn_disconnect_Click(object sender, RoutedEventArgs e) | |
{ | |
disconnect(); | |
} | |
void submit_message() | |
{ | |
if (tb_eingabe.Text != "") | |
{ | |
Send(client, tb_eingabe.Text); // + "<EOF>"??? | |
sendDone.WaitOne(); | |
lb_chat.Items.Add(name + ": " + tb_eingabe.Text); | |
tb_eingabe.Text = ""; | |
tb_eingabe.Focus(); | |
} | |
} | |
private void connectbtn() | |
{ | |
try | |
{ | |
clientPort = generate_Port(); | |
IPAddress remoIpAdress = System.Net.IPAddress.Parse(tb_ipadresse.Text); | |
IPEndPoint remoteEP = new IPEndPoint(remoIpAdress, serverPort); | |
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); | |
IPAddress localIpAddress = ipHostInfo.AddressList[0]; | |
IPEndPoint localEP = new IPEndPoint(localIpAddress, clientPort); | |
client.Bind(localEP); | |
connect(remoteEP, client); | |
tb_eingabe.IsEnabled = true; | |
lb_chat.IsEnabled = true; | |
btn_submit.IsEnabled = true; | |
tb_ipadresse.IsEnabled = false; | |
tb_eingabe.Focus(); | |
btn_connect.IsEnabled = false; | |
btn_disconnect.Visibility = System.Windows.Visibility.Visible; | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
void starteServer() | |
{ | |
try { | |
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); | |
IPAddress localIpAddress = ipHostInfo.AddressList[0]; | |
IPEndPoint localendpoint = new IPEndPoint(localIpAddress, serverPort); | |
server.Bind(localendpoint); | |
server.Listen(10); | |
Recive(server); | |
lb_chat.Items.Add(response); | |
receiveDone.WaitOne(); | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
private void disconnect() | |
{ | |
try{ | |
client.Shutdown(SocketShutdown.Both); | |
client.Close(); | |
btn_disconnect.Visibility = System.Windows.Visibility.Hidden; | |
tb_ipadresse.IsEnabled = true; | |
btn_connect.IsEnabled = true; | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
public static void connect(EndPoint remoteEP, Socket client) | |
{ | |
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); | |
connectDone.WaitOne(); | |
} | |
private static void ConnectCallback(IAsyncResult ar) | |
{ | |
try | |
{ | |
Socket client = (Socket)ar.AsyncState; | |
client.EndConnect(ar); | |
connectDone.Set(); | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
private static void Send(Socket client, String data) | |
{ | |
byte[] byteData = Encoding.UTF8.GetBytes(data); | |
client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(SendCallback), client); | |
} | |
private static void SendCallback(IAsyncResult ar) | |
{ | |
try | |
{ | |
Socket client = (Socket)ar.AsyncState; | |
int bytesSend = client.EndSend(ar); | |
sendDone.Set(); | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
private static void Recive(Socket client) | |
{ | |
try | |
{ | |
StateObjeckt state = new StateObjeckt(); | |
state.workSocket = client; | |
client.BeginReceive(state.buffer, 0, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state); | |
} | |
catch (Exception e) | |
{ | |
errorHandler(e); | |
} | |
} | |
private static void ReceiveCallback(IAsyncResult ar) | |
{ | |
StateObjeckt state = (StateObjeckt)ar.AsyncState; | |
Socket client = state.workSocket; | |
int bytesRead = client.EndReceive(ar); | |
if (bytesRead > 0) | |
{ | |
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead)); | |
client.BeginReceive(state.buffer, 0, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state); | |
} | |
else | |
{ | |
if (state.sb.Length > 1) | |
{ | |
response = state.sb.ToString(); | |
} | |
receiveDone.Set(); | |
} | |
} | |
static void fileWriter(string fileText, bool append){ | |
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt",append); | |
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); | |
file.Close(); | |
} | |
static void errorHandler(Exception errorMsg) | |
{ | |
MessageBox.Show(errorMsg.ToString()); | |
fileWriter(errorMsg.ToString(),true); | |
} | |
public static String GetTime(DateTime val) | |
{ | |
return val.ToString("yyyyMMddHHmmssffff"); | |
} | |
public int generate_Port() | |
{ | |
int help; | |
Random rnd = new Random(); | |
help = Convert.ToInt32(rnd.Next(49152, 65535)); // zufaelliger integer in dem frei verwendbaren portbereich erzeugen | |
if (port_avaliable(help)) | |
{// pruefen ob der zufaellige port noch frei ist | |
return help; | |
} | |
else | |
{ | |
generate_Port(); | |
} | |
help = 64000; | |
return help; | |
} | |
public bool port_avaliable(int help) | |
{ | |
bool isAvailable = true; | |
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); | |
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); | |
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) | |
{ | |
if (tcpi.LocalEndPoint.Port == help) | |
{ | |
isAvailable = false; | |
break; | |
} | |
} | |
return isAvailable; | |
} | |
} | |
public class StateObjeckt | |
{ | |
public Socket workSocket = null; | |
public const int bufferSize = 256; | |
public byte[] buffer = new byte[bufferSize]; | |
public StringBuilder sb = new StringBuilder(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment