代码就是最好的文档
代码演示:
// 服务端代码
public class ServerSocket {
public static void main(String[] args) throws IOException {
java.net.ServerSocket ss = new java.net.ServerSocket(65000);
while(true){
Socket socket = ss.accept();
new LengthCalculator(socket).start();
}
}
}
// 客户端代码
public class ClientSocket {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 65000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new String("小日本,去你的").getBytes());
int ch = 0;
byte[] buff = new byte[1024];
ch = inputStream.read(buff);
String content = new String(buff,0,ch);
System.out.println(content);
inputStream.close();
outputStream.close();
socket.close();
}
}
// 处理客户端请求子线程
public class LengthCalculator extends Thread {
private Socket socket;
LengthCalculator(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
int ch = 0;
byte[] buff = new byte[1024];
ch = inputStream.read(buff);
String content = new String(buff,0,ch);
System.out.println(content);
outputStream.write(String.valueOf(content.length()).getBytes());
inputStream.close();;
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
super.run();
}
}