c#网络编程 004 (线程与网络通信)

2009年1月31日星期六

c#网络编程 004 (线程与网络通信)

一、概述

线程是网络通讯程序的执行基本单元,一个或多个线程组成一个进程,是系统进程中可以并行执行的程序段,拥有起点,执行的顺序系列和一个终点。

二、在网络编程中使用多线程。

一般可以分为工作线程和用户线程,工作线程处理花大量时间的操作,例如打印100页的资料,用户线程用于处理与用户的交互。

在网络通讯中可以创建线程在网络上传递数据。

三、线程基础。

c#中System.Threading命名空间提供了大量的类和接口支持多线程。

初始化Thread类的新实例,有两种方式:

public Thread(ParameterizedThreadStart start);

public Thread(ThreadStart start);

构造函数中的参数ThreadStart、ParameterizedThreadStart委托表示此线程开始执行时要调用的方法。

还有两个构造函数,参数列表中的maxStackSize表示线程要使用的最大堆栈大小,如下:

public Thread(ParameterizedThreadStart start,int maxStackSize);

public Thread(ThreadStart start,int maxStackSize);

添加线程的例子:

using System;
using System.Threading;
namespace S.Q.S
{
class creatthread
{
//使用System.Threading命名空间中的public void 委托 Threadstart()
public void Method1()
{
Console.WriteLine("Method1 is the starting point of execution of the thread");
}
public static void Main()
{
//创建线程
creatthread newthread=new creatthread();
Thread Thread1=new Thread(new ThreadStart(newthread.Method1));
Thread1.Start();
Console.ReadLine();
}
}
}

输出结果:

D:\c#wangluo>creatthread
Method1 is the starting point of execution of the thread

为每个线程规范地起一个与其作用相关的名字,例如:

Thread newThread=new Thread(new ThreadStart(newClass.Method1));
newThread.Name="Printing";

终止线程的语法:

Thread1.Abort();

注意:这种终止并非c#立即终止线程运行,而是抛出一个异常,提供了一种可以更安全的杀死进程的机制。

挂起进程的语法:

Thread1.Suspend();

仅在一段时间内停止进程运行,然后可以继续执行,语法:

Thread1.Resume();

另外一个停止线程的方法:

Thread.Sleep(5000);

是类的静态方法,通过类名直接访问。

Sleep与Suspend方法的比较:

Sleep使用类型名称调用,指定时间内阻塞线程,立即阻塞,不能阻塞另一个线程。

Suspend使用对象名称调用,挂起直到使用Resume()方法,不是立即阻塞,可以阻塞另一个线程。

例子:

using System;
using System.Threading;
namespace S.Q.S
{
class Class1
{
public void Method1()
{
Console.WriteLine("Method1 is the starting point of excution of the thread");
}
public static void Main()
{
Class1 newclass = new Class1();
Thread Thread1=new Thread(new ThreadStart(newclass.Method1));
Thread1.Name="Sample Thread";
Thread1.Start();
Console.WriteLine("The excution of Sample Thread has started.");
Console.ReadLine();
Thread1.Abort();
}
}
}

输出结果:

D:\c#wangluo>class1
The excution of Sample Thread has started.
Method1 is the starting point of excution of the thread

不同方法对线程状态的影响:

当调用Thread.Start()方法时,线程的状态转变为Running。

当从另一个线程中调用Abort()方法时,线程的状态转变为AbortRequested。当执行Abort()方法时,线程的状态转变为Aborted

当从另一个线程中调用Suspend()方法时,线程的状态转变为SuspendRequested,当执行Abort()方法时,线程的状态转变为Suspended

当调用Resume()方法时,线程的状态转变为Running

当调用Sleep()方法时,线程的状态转变为WaitSleepJoin。在指定时间内不会运行线程。

四、多线程在网络编程中的应用。

一个可以接受多用户的请求的通讯程序

1、服务端程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace S.Q.S
{
class Threadtcpserver
{
private Socket server;
public Threadtcpserver()
{
IPAddress local=IPAddress.Parse("127.0.0.1");
IPEndPoint iep=new IPEndPoint(local,13000);
server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
server.Bind(iep);
server.Listen(20);
Console.WriteLine("等待客户机进行连接。。。");
while(true)
{
Socket client=server.Accept();
ClientThread newclient=new ClientThread(client);
Thread newthread= new Thread(new ThreadStart(newclient.ClientService));
newthread.Start();
}
}
static void Main(String[] args)
{
Threadtcpserver instance=new Threadtcpserver();
return;
}
}
class ClientThread
{
public static int connections=0;
public Socket service;
int i;
public ClientThread(Socket clientsocket)
{
this.service=clientsocket;
}
public void ClientService()
{
String data =null;
byte[] bytes=new byte[1024];
if (service!=null)
{
connections++;
}
Console.WriteLine("新客户连接建立:{0}个连接数",connections);
while((i=service.Receive(bytes))!=0)
{
data=System.Text.Encoding.ASCII.GetString(bytes,0,i);
Console.WriteLine("收到的数据:{0}",data);
data=data.ToUpper();
byte[] msg =System.Text.Encoding.ASCII.GetBytes(data);
service.Send(msg);
Console.WriteLine("发送的数据:{0}",data);
}
service.Close();
connections--;
Console.WriteLine("客户关闭连接:{0}",connections);
}

}
}

2、客户端程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace S.Q.S
{
class ClientThread
{
static void Main(String[] args)
{
Socket client;
byte[] buf=new byte[1024];
String input;
IPAddress local=IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(local,13000);
try
{
client =new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
client.Connect(iep);
}
catch(SocketException)
{
Console.WriteLine("无法连接到服务器!");
return;
}
finally
{
}
while(true)
{
//在控制台输入一条消息
input=Console.ReadLine();
if (input=="exit")
{
break;
}
client.Send(Encoding.ASCII.GetBytes(input));
int rec= client.Receive(buf);
Console.WriteLine(Encoding.ASCII.GetString(buf,0,rec));
}
Console.WriteLine("断开与服务器的连接!");
client.Close();
}
}
}

    0 评论:

    发表评论