参考网上的程序写的,仅仅都是概念,离实际应用还差十万八千里
using System.Net;
using System.Net.Sockets;
using System.Threading;
用到这三个库。
IPAddress local = IPAddress.Any;
IPEndPoint iep = new IPEndPoint(local, 9000);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(iep);
server.Listen(20);
Thread tcpThread = new Thread(new ThreadStart(TcpListen));
tcpThread.Start();
private void TcpListen()
{
while (true)
{
try
{
Socket client = server.Accept();
ClientThread newClient = new ClientThread(client);
Thread newThread = new Thread(new ThreadStart(newClient.ClientService));
newThread.Start();
}
catch { }
}
}
class ClientThread
{
public Socket client = null;
int i;
public ClientThread(Socket k)
{
client = k;
}
public void ClientService()
{
string data = null;
byte[] bytes = new byte[4096];
Console.WriteLine("新用户的连接。。。");
try
{
while ((i = client.Receive(bytes)) != 0)
{
if (i < 0)
{
break;
}
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("收到数据: {0}", data);
data = data.ToUpper();
bytes = System.Text.Encoding.ASCII.GetBytes(data);
client.Send(bytes);
}
}
catch (System.Exception exp)
{
Console.WriteLine(exp.ToString());
}
client.Close();
Console.WriteLine("用户断开连接。。。");