所谓简单是指的是:
1、服务器一次只能响应一个客户端的请求,直到和客户端断开链接才可以响应下一个客户端请求。不能多客户端链接服务器
客户端:
我们是在本机上做的测试,所以客户端所链接的host地址是用的127.0.0.1这个回环地址。端口好使用1023以上的,1023以下的端口号被系统保留。
package socket.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
public class socketclientDemo {
public socketclientDemo(){
}
public static void main(String[] args){
/*
*这一部分是用于获取命令行参数用的,如果为输入参数,那么自动打印本机主机名/ip地址
*/
if(args.length>0)
{
}
else
{
try {
InetAddress localHostAddress=InetAddress.getLocalHost();
System.out.println(localHostAddress.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//客户端打开一个socket
Socket socket=new Socket("127.0.1.1", 2016);
socket.setSoTimeout(6000);
//开启socket对应的输出和输入流
PrintWriter pw =new PrintWriter(socket.getOutputStream(),true);
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//给服务器发送信息,可以看到和JAVA IO基本是一样的
pw.println(br.readLine()+Calendar.getInstance().getTime().toString());
//pw.println(Calendar.getInstance().getTime().toString());
pw.flush();
/**
* 获取服务器发过来的信息
*/
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(socket.getInputStream()));
String result=bufferedReader.readLine();
System.out.println("Server say"+result);
pw.close();
bufferedReader.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器端程序
package server.socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
public class ServerSocketDemo {
public ServerSocketDemo() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//服务器开启一个serversocket监听2016端口,
ServerSocket serverSocket = new ServerSocket(2016);
while (true) {
//accept函数会一直阻塞这里,直到监听到客户端请求然后返回一个socket,用于双方之间的通信。建立连接后双方都是用socket进行通信,是平等的关系。
Socket socket = serverSocket.accept();
/**
* 获取客户端发送过来的信息,先获取输入流,
*/
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String resultString = bufferedReader.readLine();
System.out.println("Client say\t" + resultString);
/**
* 服务器发送信息给客户端,先获取输出流
*/
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.println("hello , i'm server" + Calendar.getInstance().getTime().toString());
printWriter.flush();
printWriter.close();
bufferedReader.close();
socket.close();
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception" + e.getMessage());
}
}
}