首页 > 代码库 > socket编程1-EchoServer
socket编程1-EchoServer
package Chapter1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private ServerSocket server;
private int port = 8000;
Socket socket;
public static void main(String[] args) throws IOException {
/*
* //返回本地主机ip地址 InetAddress addr=InetAddress.getLocalHost();
* //返回代表"222.34.5.7"的IP地址 InetAddress
* addr2=InetAddress.getByName("222.34.5.7");
* //返回域名为"www.baidu.com"的ip地址 InetAddress
* addr3=InetAddress.getByName("www.baidu.com");
*/
new EchoServer().service();
}
/**
* 服务器端程序一直监听端口,来接收客户端程序的连接请求。
* 如接收到连接请求,accept()方法就返回一个Socket对象,此对象与客户端的Socket对象形成一条通信线路,建立连接
*/
public EchoServer() throws IOException {
server = new ServerSocket(port); // 1.创建ServerSocket对象,在构造方法中指定监听的端口
System.out.println("服务器端程序启动,等待客户端程序访问");
socket = server.accept(); // 2.调用ServerSocket对象的accept()方法,来监听端口,等待客户端程序的连接请求。
System.out.println("service开始连接客户端 " + socket.getInetAddress() + ":"
+ socket.getPort());
}
public void service() {
try {
BufferedReader br;
br = getReader(socket);
PrintWriter pw = getWriter(socket);
String msg = null;
msg = br.readLine();
System.out.println("service接收到客户端数据:" + msg);
if (msg != null) {
if (msg.equals("bye")) {
pw.println("over");
System.out.println("客户端已发送\"bye\",服务端返回\"over\",将关闭服务端socket");
socket.close();
} else {
pw.println("service返回响应\"" + msg + "\"");
}
} else{
System.out.println("service 未得到客户端数据");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finally {
// if (socket != null)
// try {
// socket.close();
// System.out.println("服务端socket已关闭");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
/*
* Socket类提供了getInputStream()、getOutputStream()方法,分别返回输入流InputStream对象
* 、输出流OutputStream对象, 向输出流写数据---向对方发送数据 从输入流读数据---接收来自对方的数据
*
* InputStream socketIn=socket.getInputStream(); BufferedReader br=new
* BufferedReader(new InputStreamReader(socketIn));
*
* OutputStream socketOut=socket.getOutputStream();
* //参数true表示每写一行,PrintWriter缓存就自动溢出,把数据写到目的地 PrintWriter pw=new
* PrintWriter(socketOut,true);
*/
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
return br;
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
PrintWriter pw = new PrintWriter(socketOut, true);
return pw;
}
}
socket编程1-EchoServer