一个服务端 对应 一个客户端,双方可以通信。
1、服务端代码
public class EchoServerDemo {
public static void main(String[] args) {
// 端口号从 1024-65535
try {
ServerSocket ss = new ServerSocket(9007);
System.out.println("Server start...");
Socket socket = ss.accept();
//来自客户端信息
InputStream input = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String info = br.readLine();
System.out.println(info);
//发送给客户端信息
OutputStream output = socket.getOutputStream();
PrintStream ps = new PrintStream(output);
ps.println("Server:hello1");
output.close();
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、客户端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class EchoClientDemo {
public static void main(String[] args) {
// 连接服务器
try {
Socket socket = new Socket("localhost",9007);
System.out.println("Client connect Server succ");
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
PrintStream ps = new PrintStream(out);
ps.println("Client:hello");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String info = br.readLine();
System.out.println(info);
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}