public class Climit {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",3023);
new WriteThread("客户端:",socket).start();
new ReadThead(socket).start();
}
}
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(3023);
Socket accept = serverSocket.accept();
new WriteThread("服务端:",accept).start();
new ReadThead(accept).start();
}
}
public class ReadThead extends Thread{
private InputStream is;
private Socket socket;
public ReadThead(Socket socket) throws IOException {
this.socket = socket;
this.is = socket.getInputStream();
}
@Override
public void run() {
byte[] b = new byte[1024];
try {
while (true){
int len = is.read(b);
System.out.println(new String(b, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeAll(is,socket);
}
}
public class WriteThread extends Thread{
private String name;
private BufferedWriter bw;
private BufferedReader br;
private Socket socket;
public WriteThread(String name,Socket socket) throws IOException {
this.name = name;
this.socket = socket;
this.bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.br = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
try {
while (true) {
bw.write(name+":"+br.readLine());
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeAll(bw,socket);
}
}
}
|