客户端向服务端发送消息,服务端返回消息
public class TestSocket {
//客户端向服务端发送消息,服务端返回消息
public static void main(String [] args) {
Socket s = null;
try {
s = new Socket("127.0.0.1", 8888);
String str = "你好,我是Client"; //需要发送到服务端的字符串
//发送字符串,建议使用PrintWriter
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(str);
//客户端接收来自服务端的消息
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("来自服务端的消息:" + br.readLine());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class TestServerSocket {
//客户端向服务端发送消息,服务端返回消息
public static void main(String [] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888);
Socket s = ss.accept();
String str = "你好,我是Server";
//读取字符串,建议使用BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("来自客户端的消息:" + br.readLine());
//服务端向客户端发送消息
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(str);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}