1. 使用TCP的套接字编写一个服务端,一个客户端服务端有一个Map,里面存放的是这些内容。
key:andy, value:192.168.1.6
key:candy, value:192.168.1.9
key:bob, value:192.168.1.10
key:sucy, value:192.1 68.1.15
客户端发送key给服务端,服务器返回value。
如:客户端发送andy,服务器返回: 192.168.1.6
(1)服务器端:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class Server {
public static void main(String[] args) throws Exception {
//1.创建服务器套接字,并监听指定端口
ServerSocket server = new ServerSocket(9090);
System.out.println("服务器正在连接........");
//2.从队列中获取客户端的连接
Socket socket = server.accept();
//3.创建输入输出流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//4.创建一个map用来存储
Map <String, String>map=new HashMap<String, String>();
map.put("andy", "192.168.1.6");
map.put("candy", "192.168.1.9");
map.put("bob", "192.168.1.10");
map.put("sucy", "192.168.1.15");
//5.创建字节缓冲区
byte[] buff=new byte[1024];
int cnt=0;
String msg;
//6.读取来自客户端的数据
if ((cnt=is.read(buff))!=-1) {
//把字节缓冲区内容转成字符串
msg=new String(buff,0,cnt);
//foreach循环遍历map,并发送数据到客户端
for(Map.Entry<String, String> entry : map.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
//判断客户端传来的值是否等于map的键
if (msg.equals(mapKey)) {
//6.如果等于,把map对应的值发送数据给客户端
os.write(mapValue.getBytes());
}
}
}
server.close();
}
}
(2)客户端:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception{
//1.创建客户端套接字,并绑定ip和端口号
Socket socket=new Socket("localhost", 9090);
//2.创建输入输出流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
Scanner scanner=new Scanner(System.in);
System.out.print("请输入Key:");
String msg1=scanner.nextLine();
//3.把输入的信息发送服务器;
os.write(msg1.getBytes());
//4.创建字节缓冲区
byte[] buff=new byte[1024];
int cnt=0;
String msg2;
//5.读取服务器传回来的信息
if ((cnt=is.read(buff))!=-1) {
//把字节缓冲区内容转成字符串
msg2=new String(buff,0,cnt);
System.out.println("接收到的数据为:"+msg2);
}
//6.关闭资源
socket.close();
}
}