1.import java.io.*;
import java.net.*;
public class Server {
public static final int PORT=8888;
public static void main(String[] args) throws IOException{
ServerSocket ss=new ServerSocket(PORT);
System.out.println(ss);
try{
//记录客户端的数量
int count=0;
System.out.println("***服务器即将启动,等待客户端的连接***");
//循环监听,等待客户端的连接
while(true){
Socket socket=ss.accept();
//创建新线程
ServerThread serverThread=new ServerThread(socket);
//启动线程
serverThread.start();
count++;
System.out.println("客户端的数量:"+count);
InetAddress address=socket.getInetAddress();
System.out.println("当前客户端的IP:"+address.getHostAddress());
}
}catch(IOException e){
e.printStackTrace();
}finally{
ss.close();
}
}
}
2.import java.io.*;
import java.net.*;
/*
-
服务器线程处理类
*/
public class ServerThread extends Thread{
//和本线程相关的socket
Socket socket=null;public ServerThread(Socket socket) {
this.socket = socket;
}//线程执行的操作,响应客户端的请求
@Override
public void run() {BufferedReader in=null; PrintWriter out=null; try{ //获取输入输出流 in=new BufferedReader( new InputStreamReader( socket.getInputStream())); String info=null; while((info=in.readLine())!=null){ System.out.println("我是服务器,客户端说"+info); } socket.shutdownInput(); out=new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()))); out.println("welcome!"); out.flush();//调用flush()方法将缓冲输出 }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(in!=null) in.close(); if(out!=null) out.close(); }catch(IOException e){ e.printStackTrace(); } }
}
}
3.import java.io.*;
import java.net.*;
/*
-
客户端
*/
public class Client {
public static void main(String[] args)throws IOException {
Socket socket=new Socket("localhost",Server.PORT);
try{
BufferedReader in=new BufferedReader(
new InputStreamReader(
socket.getInputStream()));PrintWriter out=new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()))); out.println("用户名:mtone;密码:123"); out.flush(); //flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满 socket.shutdownOutput(); String info=null; info=in.readLine(); while(info!=null){ System.out.println("我是客户端,服务器说:"+info); } }catch(IOException e){ e.printStackTrace(); }finally{ socket.close(); }
}
}