Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur

9 Ocak 2011 Pazar

C# ile Thread lenmiş İstemci-Sunucu


Ref: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server

Sunucu



using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace newServer
{
public partial class FrmServer : Form
{
public FrmServer()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}

private TcpListener tcpListener;
private Thread mainThread;
private void Form1_Load(object sender, EventArgs e)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
mainThread = new Thread(ListenMainThread);
mainThread.Start(tcpListener);
}

public void ListenMainThread(object listener)
{
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
lbLog.Items.Add("Bağlantı geldi");
Thread clientThread = new Thread(HandleClientComm);
clientThread.Start(client);
}
}

public void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient) client;
NetworkStream clientStream = tcpClient.GetStream();

byte[] message = new byte[4096];
int bytesRead;

while (true)
{
bytesRead = 0;

try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}

if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}

//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
string okunan = encoder.GetString(message, 0, bytesRead);
lbLog.Items.Add("Okundu: " + okunan);
}

tcpClient.Close();
}
}
}


İstemci



using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace NewClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 3000);
NetworkStream nsClient = client.GetStream();
for (int i = 0; i < 10; i++)
{
string sMesaj = "Merhaba " + i;
byte[] barrMesaj = Encoding.ASCII.GetBytes(sMesaj);
int iLen = barrMesaj.Length;
nsClient.Write(barrMesaj,0,iLen);
Thread.Sleep(1000);
}
}
}
}

Hiç yorum yok: