Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //form1
- namespace SockProgram
- {
- public partial class loginForm : Form
- {
- public Socket sock = new SockProgram.Socket();
- public loginForm()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- if (this.inputusername.Text.Length > 1 && this.inputpassword.Text.Length > 1)
- {
- sock.connect();
- sock.send("hello\r\n");
- sock.username = this.inputusername.Text;
- sock.password = this.inputpassword.Text;
- }
- }
- }
- }
- //Socket.cs
- namespace SockProgram
- {
- public class Socket
- {
- NetworkStream ns;
- System.Windows.Forms.Timer sockRead = new Timer();
- int connected = 0;
- string str_username;
- string str_password;
- int loggedin = 0;
- public string username
- {
- get { return str_username; }
- set { str_username = value; }
- }
- public string password
- {
- get { return str_password; }
- set { str_password = value; }
- }
- int isConnected
- {
- get { return connected; }
- set { connected = value; }
- }
- public Socket()
- {
- return;
- }
- public void connect()
- {
- TcpClient server;
- try
- {
- server = new TcpClient("servon.dk", 1000);
- }
- catch (SocketException)
- {
- MessageBox.Show("Kunne ikke connecte til server.");
- return;
- }
- ns = server.GetStream();
- connected = 1;
- Debug.WriteLine("Connected..");
- sockRead.Interval = 20;
- sockRead.Enabled = true;
- sockRead.Tick += new EventHandler(sockRead_Tick);
- }
- void sockRead_Tick(object sender, EventArgs e)
- {
- string stringData;
- int bytes;
- if (ns.DataAvailable)
- {
- byte[] data = new byte[1024];
- bytes = ns.Read(data, 0, data.Length);
- stringData = Encoding.ASCII.GetString(data, 0, bytes);
- Debug.WriteLine("<- " + stringData);
- handleInput(stringData);
- }
- }
- public void send(string text)
- {
- if (isConnected == 1)
- {
- ns.Write(Encoding.ASCII.GetBytes(text), 0, text.Length);
- ns.Flush();
- Debug.WriteLine("-> " + text);
- }
- }
- public void handleInput(string input)
- {
- string[] words = input.Split(' ');
- int code = System.Convert.ToInt32(words[0]);
- Debug.WriteLine("Code: " + code);
- switch (code)
- {
- case 1:
- Debug.WriteLine("Handshake ok");
- /* Do login */
- send("USER " + username + "\n");
- send("PASS " + password + "\n");
- break;
- case 2:
- MessageBox.Show("Du bruger en forkert version af programmet, update plz");
- break;
- case 3:
- MessageBox.Show("Brugernavn ikke fundet");
- break;
- case 4:
- MessageBox.Show("Forkert kode");
- break;
- case 5:
- loggedin = 1;
- Form mainForm = new mainForm();
- break;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment