/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.programe.ten;
import com.macfaq.io.*;
import java.io.*;
import java.net.*;
/**
*
* @author Arthur
*/
public class ClientTester {
public static void main(String[] args) {
int port = 80;
Socket conn = null;
try {
//创建端口号为port,队列长度为1的server,设置为1.说明此服务器只能接收一个连接
ServerSocket server = new ServerSocket(port, 1);
System.out.println("在端口" + server.getLocalPort() + "监听");
while (true) {
//开始接收客户端的连接请求,把每一个连接返回的conn放入线程里面S
conn = server.accept();
try {
System.out.println("开始在" + conn + "连接");
//用来读取客户端发来的消息
Thread input = new InputThread(conn.getInputStream());
input.start();
//用来向客户端发送消息
Thread out = new OutputThread(conn.getOutputStream());
out.start();
//加入主线程等待输入和输出结束
try {
input.join();
out.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}//end while
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}//end finally
}//end main
}
/**
* 定义一个输入流线程,用来读取某个客户端发来的消息
* @author Arthur
*/
class InputThread extends Thread {
InputStream in;
public InputThread(InputStream in) {
this.in = in;
}
@Override
public void run() {
try {
while (true) {
//一次读取一个字节
int i = in.read();
//如果读完,跳出循环
if (i == -1) {
break;
}
System.out.println(i);
}//end while
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
System.err.println(ex);
}
try {
in.close();
} catch (IOException ex) {
}
}//end run
}
/**
* 定义一个输出流线程,用来向某个客户端发送消息
* @author Arthur
*/
class OutputThread extends Thread {
private Writer out;
public OutputThread(OutputStream out) {
this.out = new OutputStreamWriter(out);
}
@Override
public void run() {
//用来存储控制台输入的一行内容
String line;
//从控制台获取数据
BufferedReader in = new SafeBufferedReader(new InputStreamReader(System.in));
while (true) {
try {
line = in.readLine();
//以问号结束循环
if (line.equals("?")) {
break;
}
//把控制台的数据发送出去
out.write(line + "\r\n");
//刷新
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}//end while
try {
out.close();
} catch (IOException ex) {
}
}// end run
}
一个客户端测试器(摘自《java网络编程》)
关注
打赏