import java.net.*;
import java.io.*;
class Server
{
Server()
{
try
{
//服务器监听
ServerSocket listen = new ServerSocket(8888);
//等待有人来没有,如果有了,形成响应的socket,如果没有,一直忙等待
Socket socket = listen.accept();
//找到收发接口
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//对收发接口进行封装
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintWriter pw = new PrintWriter(os,true);
//循环收发10次
for(int i=0;i<10;i++)
{
//接受数据
String info = br.readLine();
System.out.println("from client:"+info);
//发送数据
pw.println("当我还是年轻健壮.....");
}
//释放资源,注意释放顺序
br.close();
pw.close();
is.close();
os.close();
socket.close();
listen.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String s[])
{
new Server();
}
}
网友评论