62,614
社区成员
发帖
与我相关
我的任务
分享
/**
*
*接收Client数据的服务线程
*
*/
class ClientServer extends Thread{
private ServerSocket ss;
private int PORT;
private DataSCalcServer dscs;
public ClientServer(int port,DataSCalcServer dscs){
this.PORT = port;
this.dscs = dscs;
}
public void run(){
ExecutorService execPool = null;
try{
ss = new ServerSocket(PORT);
// execPool = Executors.newFixedThreadPool(25); //创建固定大小的线程池* A处
while(true){
Socket socket = ss.accept();
// execPool.execute(new clientThread(socket));
new clientThread(socket).start();
}
}catch(IOException ioe){
execPool.shutdown();
System.out.println("Error ss.accept():"+ioe.getMessage());
}
}
class clientThread extends Thread{
private PrintWriter pw ;
private BufferedReader br ;
private Socket socket;
public clientThread(Socket socket){
this.socket = socket;
try{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream());
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
boolean status = true;
try{
while(status){
try{
if(br != null){
String str = br.readLine().trim();
String packet = dscs.setToClientPacket(str); //打包发送给Client
if(packet != null){
pw.println(packet);
pw.flush();
}
}
sleep(1); //B处
}catch(Exception e){
status = false;
System.out.println("Warning delphiClient interrupted ....");
e.printStackTrace();
}
}
}catch(Exception e){
System.out.println("Error run():"+e.getMessage());
}finally{
try{
if(br != null)
br.close();
if(pw != null)
pw.close();
if(socket != null)
socket.close();
}catch(Exception e){
System.out.println("Error close failed.");
}
}
}
}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
/**
* 非堵塞式 Server Socket 示例
* @author hbwhwang
*
*/
public class NonBlockServer extends Thread {
static final int PORT = 19001;
private ByteBuffer dataBuffer = ByteBuffer.allocate(1024);
private Selector selector = null;
private Charset charset = Charset.forName("GB2312");
public NonBlockServer() {
try {
startup();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startup() throws IOException {
selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ServerSocket ss = ssc.socket();
ss.bind(new InetSocketAddress(PORT));
ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server startup...");
}
/**
* 业务处理方法,这里只简单地返回系统时间
* @return
*/
public String bizMethod(){
return String.valueOf(System.nanoTime());
}
public void run() {
if (selector==null)
return;
while (true) {
try {
int num = selector.select();
if (num==0){
Thread.yield();
continue;
}
} catch (IOException e) {
e.printStackTrace();
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc=null;
try {
sc = ssc.accept();
sc.configureBlocking(false);
// Add the new connection to the selector
sc.register(selector, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Got connection from "
+ sc.socket().getInetAddress() + ":"
+ sc.socket().getPort());
} else if (key.isReadable()) {
// Read the data
SocketChannel sc = (SocketChannel) key.channel();
dataBuffer.clear();
try {
//这里未对读入的信息处理。在实际环境中,可能读到的是指令。另外也可能一次读不完,那么需要考虑多次读
int r = sc.read(dataBuffer);
sc.register(selector, SelectionKey.OP_WRITE);
} catch (IOException e) {
e.printStackTrace();
}
dataBuffer.flip();
CharBuffer cb=charset.decode(dataBuffer);
String temp=cb.toString();
System.out.println("Read data from "
+ sc.socket().getInetAddress() + ":"
+ sc.socket().getPort() + " - "
+ temp+",length:"+temp.length());
} else if (key.isWritable()) {
dataBuffer.clear();
//这里没有考虑一次写不完的情况。。。
dataBuffer.put(bizMethod().getBytes());
dataBuffer.put("\n".getBytes());
dataBuffer.flip();
SocketChannel sc = (SocketChannel) key.channel();
try {
sc.write(dataBuffer);
sc.register(selector, 0);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Write to ..."
+ sc.socket().getInetAddress() + ":"
+ sc.socket().getPort());
}
}
}
}
public static void main(String[] args) throws IOException {
new NonBlockServer().start();
}
}
import java.net.*;
import java.io.*;
public class JabberClient extends Thread {
public void run(){
try {
InetAddress addr;
addr = InetAddress.getByName("localhost");
Socket socket = new Socket(addr, NonBlockServer.PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.print("howdy");
out.flush();
String str = in.readLine();
socket.close();
System.out.println(str);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
for (int i=0;i<10;i++){
new JabberClient().start();
}
}
} // /:~