TCP Lectrue One
TCP Lectrue One
Server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace TcpPreparingServer
{
public partial class frmServer : Form
{
public frmServer()
{
InitializeComponent();
}
namespace TcpPreparingClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
1
IPEndPoint ipEnd = new IPEndPoint(ip, 8090);
TcpClient client = new TcpClient();
client.Connect(ipEnd);
byte[] bToSend = Encoding.Unicode.GetBytes("hello");
client.GetStream().Write(bToSend, 0, bToSend.Length);
}
}
}
namespace TcpPreparingServer
{
public partial class frmServer : Form
{
public frmServer()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
2
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace TcpPreparingClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
namespace TcpPreparingServer
{
public partial class frmServer : Form
{
public frmServer()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
3
IPAddress ip = IPAddress.Parse("0.0.0.0");
IPEndPoint ipEnd = new IPEndPoint(ip, 8090);
TcpListener listener = new TcpListener(ipEnd);
listener.Start();
new Thread(() =>
{
while (true)
{
TcpClient client = listener.AcceptTcpClient();
byte[] bReceived = new byte[1024];
new Thread(() =>
{
while (true)
{
Array.Clear(bReceived, 0,
bReceived.Length);
client.GetStream().Read(bReceived, 0,
bReceived.Length);
string s =
Encoding.Unicode.GetString(bReceived);
lstMessages.Items.Add(s);
}
}).Start();
}
}).Start();
}
}
}
Client is same as client in program two but now you can run more than one program
at the same time.
Assignment:
1.How you can in server display the message received from which client for example
client accepted first call it client 1 and client accepted second would be client 2….
2.How can you make the server in program three return messages to specific client
that connected to it. For example you can add a second ListBox to your program and
the client accepted first add it to the list and call it client 1 and client accepted second
add it to the list and call it client 2… then add TextBox txtMessage and Button
btnSend then when you select the client and write a word in TextBox and click send it
will be sent to the selected client.
3.In code show how could you display the messages in server from a client only if it
has user name and password in the Server.
Good Luck