class TcpServerDemo {
public static void main(String[] args) throws IOException {
System.out.println("Server start ...");
ServerSocket ss = new ServerSocket(10005);
Socket s = ss.accept();
System.out.println("Connected :" + s.getInetAddress().getHostAddress().toString() + " port:" + s.getPort());
while (true) {
System.out.println("等待接收消息:");
InputStream in = s.getInputStream();
byte[] data = new byte[1024];
int len = in.read(data);
String str = new String(data, 0, len);
if ("886".equals(str)) {
System.out.println("bye");
ss.close();
s.close();
System.exit(0);
}
System.out.println(str);
System.out.println("发信息:");
BufferedReader ins = new BufferedReader(new InputStreamReader(System.in));
OutputStream out = s.getOutputStream();
out.write(ins.readLine().getBytes());
}
}
}
/**
* 给服务端发送一个文本数据
*/
class TcpClientDemo {
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 10005);
while (true) {
System.out.println("发信息:");
BufferedReader ins = new BufferedReader(new InputStreamReader(System.in));
String str = ins.readLine();
OutputStream out = s.getOutputStream();
out.write(str.getBytes());
if ("886".equals(str)) {
System.out.println("bye");
s.close();
System.exit(0);
}
System.out.println("等待回复中:");
InputStream in = s.getInputStream();
byte[] data = new byte[1024];
int len = in.read(data);
System.out.println(new String(data, 0, len));
}
}
}