Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1500022
  • 博文数量: 108
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 997
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-29 09:58
个人简介

兴趣是坚持一件事永不衰竭的动力

文章分类

全部博文(108)

文章存档

2021年(1)

2020年(10)

2019年(19)

2018年(9)

2016年(23)

2015年(43)

2013年(3)

我的朋友

分类: Java

2015-11-17 23:43:43

package com.ddChat.Test;


import java.io.IOException;
import java.net.InetAddress;
/**
 * 这段代码执行以后,在客户端将会有3个通讯线程,每个线程首先将先向服务器端发送"Hello Server,My id is "的字符串,然后发送”byebye”,终止该线程的通讯。
 * 
 * 运行效果演示 
接下来,我们来观察一下基于多线程的C/S架构的运行效果。 
 
第一步,我们先要启动服务器端的ThreadServer代码,启动后,在控制台里会出现如下的提示信息:  
The Server is start: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=3333]  
上述的提示信息里,我们同样可以看到,服务器在开启服务后,会阻塞在accept这里,直到有客户端请求过来。 
 
第二步,我们在启动完服务器后,运行客户端的ThreadClient.java代码,运行后,我们观察服务器端的控制台,会出现如下的信息: 
 
The Server is start: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=3333]  
In Server reveived the info: Hello Server,My id is 0  
In Server reveived the info: Hello Server,My id is 1  
In Server reveived the info: Hello Server,My id is 2  
closing the server socket!  
close the Server socket and the io.  
closing the server socket!  
close the Server socket and the io.  
closing the server socket!  
close the Server socket and the io. 
 
其中,第一行是原来就有,在后面的几行里,首先将会输出了从客户端过来的线程请求信息,比如  
In Server reveived the info: Hello Server,My id is 0  
接下来则会显示关闭Server端的IO和Socket的提示信息。
这里,请大家注意,由于线程运行的不确定性,从第二行开始的打印输出语句的次序是不确定的。但是,不论输出语句的次序如何变化,我们都可以从中看到,客户端有三个线程请求过来,并且,服务器端在处理完请求后,会关闭Socker和IO。 
 
第三步,当我们运行完ThreadClient.java的代码后,并切换到ThreadClient.java的控制台,我们可以看到如下的输出:  
Hello Server,My id is 0  
Hello Server,My id is 2  
Hello Server,My id is 1  
这说明在客户端开启了3个线程,并利用这3个线程,向服务器端发送字符串。 
 
而在服务器端,用accept方法分别监听到了这3个线程,并与之对应地也开了3个线程与之通讯。


 * @author Administrator
 *
 */
public class ThreadClient
{
public static void main(String[] args) throws IOException, InterruptedException
{
int threadNo = 0;
InetAddress addr =


InetAddress.getByName("localhost");
for (threadNo = 0; threadNo < 3; threadNo++)
{
new ClientThreadCode(addr);
}
}
}

阅读(1965) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~