鉴于ServerSocket的accept方法是阻塞的,那么只能通过多线程的方式实现多客户端连接与服务器连接
基本步骤:
1,服务端创建ServerSocket绑定端口号,循环调用accept()方法
2,客户端创建一个socket并请求和服务器端连接
3,服务器端接受客户端请求,创建socket与该客户建立连接
4,两个socket在一个单独的线程上通话
5,服务器端继续等待新的连接
也就是说当有一个新的客户端与服务端连接,就创建一个新的socket并在这个线程里面通信。
服务端代码:
multithreadingServer.class:
public class multithreadingServer {
public static void main(String[] args) {
try {
ServerSocket serversocket=new ServerSocket(8888);
Socket socket=null;
int n=0;
while(true){
socket=serversocket.accept();//再来一个客户端就新建一个socket
ServerThread serverthread=new ServerThread(socket);
serverthread.start();
n++;
System.out.println("已有"+n+"台客户端连接");
InetAddress address=socket.getInetAddress();//获取客户端的inetaddress对象
System.out.println("当前主机ip:"+address.getHostAddress());//获取客户端的ip
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerThread.class:
public class ServerThread extends Thread{//服务器线程处理类
Socket socket=null;
InputStream is=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
try {
is=socket.getInputStream();//获得字节流
br=new BufferedReader(new InputStreamReader(is));//字节流转化为字符流并添加缓冲
String info=null;
while((info=br.readLine())!=null){
System.out.println("我是服务端,客户端说:"+info);
}
socket.shutdownInput();//必须要及时关闭,因为readline这个方法是以\r\n作为界定符的,由于发送消息的那一端用的是PrintWriter的write()方法,这个方法并没加上\r\n,所以会一直等待
//回复客户端
os=socket.getOutputStream();
pw=new PrintWriter(os);
pw.write("欢迎您!");
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (pw!=null)
pw.close();
try {
if (os!=null)
os.close();
if (br!=null)
br.close();
if (is!=null)
is.close();//关闭返回的 InputStream 将关闭关联套接字。
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端代码保持不变:
public class client {
public static void main(String[] args) {
try {
Socket socket=new Socket("127.0.0.1",8888);//创建客户端socket,因为是本地,ip地址就是127.0.0.1
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("用户名:admin;密码:123");
pw.flush();
socket.shutdownOutput();//必须加上这句话,表示输出流的结束,注意此时不能关闭os,因为关闭os会关闭绑定的socket
//在客户端获取回应信息
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String info=null;
while((info=br.readLine())!=null){
System.out.println("我是客户端,服务端说:"+info);
}
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}