实现的功能
客户端发送消息到服务端,服务端收到后打印该消息并给客户端反馈信息
基本思路
使用类 ServerSocket,创建一个绑定到特定窗口的服务器套接字。
然后用它的accept方法侦听客户端对其的连接,并接受其发送的Socket。
Socket有一个获取输入输出流的方法。
如果要发送消息,使用输出流。
如果要接受消息,使用输入流。
服务端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class UpperServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(23333);
Socket s = ss.accept();
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
PrintWriter out = new PrintWriter(bufOut, true);
System.out.println("From: " + s.getInetAddress().getHostAddress());
String str;
//readLine方法需要读到换行符
//缓冲区需要使用flush刷新才能发送
while ((str = bufIn.readLine()) != null) {
System.out.println(str);
out.println(str.toUpperCase());
/*
bufOut.write(str.toUpperCase());
bufOut.newLine();
bufOut.flush();
*/
}
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class UpperClient {
public static void main(String[] args) {
try {
Socket s = new Socket("192.168.149.1", 23333);
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
PrintWriter out = new PrintWriter(bufOut, true);
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
String str;
while ((line = bufr.readLine()) != null) {
//bufOut.write(line);
//bufOut.newLine();
// bufOut.flush();
if (line.equals("over")) {
break;
}
out.println(line);
str = bufIn.readLine();
System.out.println("Server: " + str);
}
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
END