客户端代码
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
BufferedReader br = null;
PrintWriter pw = null;
try {
Socket socket = new Socket("127.0.0.1", 8800);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("Hello");
String s = null;
while (true) {
s = br.readLine();
if (s != null) {
break;
}
}
System.out.println(s);
}catch (Exception ex){
ex.printStackTrace();
}finally {
try{
br.close();
pw.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}
服务端代码
package cool.islj;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args){
BufferedReader br = null;
PrintWriter pw = null;
try{
ServerSocket server = new ServerSocket(8800);
Socket socket = server.accept();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
// 读取,然后再发送回去
String s = br.readLine();
pw.println(s);
}catch (Exception ex){
ex.printStackTrace();
}finally {
try{
br.close();
pw.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}