server
public class Server {
public static void main(String[] args) throws IOException, IOException {
int i = 0;
String taskId;
ServerSocket serverSocket = new ServerSocket(6666);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
System.out.println(scanner.nextLine());
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println("hello output");
// 释放资源
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
}
}
client
public class Client {
public static void main(String[] args) throws IOException, IOException {
int i;
Socket socket = new Socket("localhost", 6666);
// 写数据到服务器
OutputStream outputStream = socket.getOutputStream();
outputStream.write("mytask".getBytes());
// 关闭当前输出流,同时关闭了服务器的输入流(此方法必须要,否则无法正常读写)
socket.shutdownOutput();
// 读服务类写来的数据
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
System.out.println(scanner.nextLine());
socket.shutdownInput();
// 释放资源
outputStream.close();
inputStream.close();
socket.close();
}
}
网友评论