服务端
public static void main(String[] args) throws IOException {
int port = 30000;//端口号
//1、创建ServerSocket 绑定监听端口
ServerSocket serverSocket = new ServerSocket(port);
//2、调用accept方法开始监听,客户端连接后,返回Socket
System.out.println("====等待客户端连接=======");
Socket socket = serverSocket.accept();
//3、连接成功后,获取InputStream,读取客户端发来信息
System.out.println("===已连接:" + socket.isConnected() + "======");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//4、当获取的信息不为exit时,循环接收
while (true) {
String info = br.readLine();
if (!info.isEmpty()) {
System.out.println(info);
}
if (info.equals("exit")) {
br.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
serverSocket.close();
}
}
客户端
//端口号和服务端地址
int port = 30000;
InetAddress address = InetAddress.getLocalHost();//获取本地地址
//1、获取访问服务端的Socket对象,建立与服务端的连接
Socket socket = new Socket(address,port);
System.out.println("=====已连接:"+ socket.isConnected()+"======");
//是否连接
//2、获取输出流
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
String message ="您好,服务端!";
pw.println(message);
//3、自己输入信息,发送给服务端,并获得响应
Scanner scanner = new Scanner(System.in);
while(true){
String s = scanner.nextLine();
pw.println(s);
if(s.equals("exit")){
break;
}
}
out.close();
pw.close();
socket.close();
Android Studio 不支持在同一个模块中运行两个JAVA 程序,它们的运行是同步的,因此需要重开一个Android Project.