socket

服务器端

package io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoServer {
private int port = 8000;
private ServerSocketChannel serverSocketChannel = null;
private ExecutorService executorService;
private static final int POOL_MULTIPLE = 4;

public EchoServer() throws IOException {
// 创建线程池
executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors() * POOL_MULTIPLE);
// 创建ServerSocketChannel对象
serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().setReuseAddress(true);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
System.out.println("服务器是" + Runtime.getRuntime().availableProcessors()
+ "核的");
System.out.println("服务器启动");
}

public void service() {
while (true) {
SocketChannel socketChannel = null;
try {
socketChannel = serverSocketChannel.accept();
executorService.execute(new Handler(socketChannel));
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) throws IOException {
new EchoServer().service();
}

class Handler implements Runnable {
private SocketChannel socketChannel;

public Handler(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
}

public void run() {
handle(socketChannel);
}

public void handle(SocketChannel socketChannel) {
try {
Socket socket = socketChannel.socket();
System.out.println("收到客户链接来自" + socket.getInetAddress() + ":"
+ socket.getPort());

BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);

String msg = null;
while ((msg = br.readLine()) != null) {
System.out.println("from client:"+msg);
pw.println(echo(msg));
if (msg.equals("bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream out = socket.getOutputStream();
return new PrintWriter(out, true);
}

private BufferedReader getReader(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
return new BufferedReader(new InputStreamReader(in));
}

public String echo(String msg) {
return "from server echo:" + msg;
}
}
}


客户端

Socket socket = new Socket("localhost", 8000);
socket.getOutputStream().write(
("111111" + System.getProperty("line.separator")).getBytes());


服务器端是读到终止符才会读
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值