一个简单的Socket实例
- 使用socket实现通信;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8899);
serverSocket.setReuseAddress(true);
System.out.println("服务器启动,等待连接");
Socket socket = serverSocket.accept();
if(null != socket){
System.out.println("客户端:" + socket.getInetAddress() + "已建立连接");
OutputStream os = socket.getOutputStream();
os.write("hello\r\n".getBytes());
os.flush();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
System.out.println("收到客户端信息:" + line);
os.close();
br.close();
}
}
}
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8899);
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
System.out.println("接收到服务器消息:" + line);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("I am coming from client.");
ps.flush();
ps.close();
br.close();
}
}
- 使用NIO实现通信。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
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.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class NioServer {
private static Map<String,SocketChannel> clientMap = new HashMap<>();
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
ServerSocket socket = serverSocketChannel.socket();
socket.bind(new InetSocketAddress(8899));
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while(true){
try {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
selectionKeys.forEach(selectionKey -> {
final SocketChannel client;
try{
if(selectionKey.isAcceptable()) {
ServerSocketChannel channel =
(ServerSocketChannel) selectionKey.channel();
client = channel.accept();
client.configureBlocking(false);
client.register(selector,SelectionKey.OP_READ);
String key = "[" + UUID.randomUUID().toString() + "]";
clientMap.put(key,client);
}else if(selectionKey.isReadable()){
client = (SocketChannel)selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = client.read(buffer);
if(count > 0){
buffer.flip();
Charset charset = Charset.forName("UTF-8");
String receiveMessage =
String.valueOf(charset.decode(buffer).array());
System.out.println(client + ":" + receiveMessage);
String senderKey = null;
for(Map.Entry<String,SocketChannel> entry:
clientMap.entrySet()){
if(client == entry.getValue()){
senderKey = entry.getKey();
break;
}
}
for(Map.Entry<String,SocketChannel> entry:
clientMap.entrySet()){
SocketChannel value = entry.getValue();
ByteBuffer writeBuffer =
ByteBuffer.allocate(1024);
writeBuffer.put((senderKey + ":"
+ receiveMessage).getBytes());
writeBuffer.flip();
value.write(writeBuffer);
}
}
}
selectionKeys.clear();
}catch (IOException e){
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NioClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);
socketChannel.connect(new InetSocketAddress("localhost",8899));
while(true){
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
for(SelectionKey selectionKey:selectionKeys){
if(selectionKey.isConnectable()){
SocketChannel client = (SocketChannel)selectionKey.channel();
if(client.isConnectionPending()){
client.finishConnect();
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
writeBuffer.put((LocalDateTime.now()
+ "连接成功").getBytes());
writeBuffer.flip();
client.write(writeBuffer);
ExecutorService executorService =
Executors.newSingleThreadExecutor(
Executors.defaultThreadFactory());
executorService.submit(()->{
while(true){
writeBuffer.clear();
InputStreamReader input =
new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(input);
String sendMessage = br.readLine();
writeBuffer.put(sendMessage.getBytes());
writeBuffer.flip();
client.write(writeBuffer);
}
});
}
client.register(selector,SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
SocketChannel client = (SocketChannel) selectionKey.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int count = client.read(readBuffer);
if(count > 0){
String receivedMessage =
new String(readBuffer.array(),0,count);
System.out.println(receivedMessage);
}
}
}
selectionKeys.clear();
}
}
}