1.服务器端代码:
public class Service {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
System.out.println(reader.readLine());
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.客户端:
public class User {
public static void main(String[] args) {
while (true) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String s = reader.readLine();
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
writer.println(s);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}