# bio
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
System.out.println("Start to accept.");
Socket socket = serverSocket.accept();
new Thread(() -> {
try {
handler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
public static void handler(Socket socket) throws IOException{
byte[] bytes = new byte[1024];
int read = socket.getInputStream().read(bytes);
if (read != -1) {
System.out.println(new String(bytes, 0, read));
}
}
}
# nio import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.*; public class SocketServer { private static final Set<SocketChannel> socketChannels = new HashSet<>(); public static void main(String[] args) throws Exception{ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9000)); serverSocketChannel.configureBlocking(false); while (true) { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { socketChannel.configureBlocking(false); socketChannels.add(socketChannel); } Iterator iterator = socketChannels.iterator(); while (iterator.hasNext()) { SocketChannel socketChannel1 = (SocketChannel) iterator.next(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int len = socketChannel1.read(byteBuffer); if (len > 0) { System.out.println(new String(byteBuffer.array())); } if (len == -1){ socketChannels.remove(socketChannel1); } } } } }
标签:java,socket,read,编程,new,import,public From: https://www.cnblogs.com/wzllzw/p/16630896.html