62,612
社区成员
发帖
与我相关
我的任务
分享
package chapter01.example11;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
Thread.sleep(5000);
InputStream in=s.getInputStream();
ByteArrayOutputStream buffer=new ByteArrayOutputStream();
byte[] buff=new byte[1024];
int len=-1;
do {
len=in.read(buff);
if(len!=-1)
buffer.write(buff,0,len);
} while (len!=-1);
System.out.println(new String(buffer.toByteArray()));
}
}
package chapter01.example10;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SimpleClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("localhost",8000);
s.setSoLinger(true, 3600);
OutputStream out=s.getOutputStream();
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
out.write(sb.toString().getBytes());
System.out.println("开始关闭");
long begin=System.currentTimeMillis();
s.close();
long end=System.currentTimeMillis();
System.out.println("关闭Socket所用的时间未:"+(end-begin)+"ms");
}
}