server端
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]){
try{
//服务器监听8888端口等待客户端的请求
ServerSocket serverSicket= new ServerSocket(8888);
Socket socket=null;
//接受客户端的socket
System.out.println("正在等待客户端的请求");
int count=0;
while(true){
//调用accept()方法开始监听客户端的请求
socket=serverSicket.accept();
//创建一个新的线程
ServerThread serverThread=new ServerThread(socket);
//启动线程
serverThread.start();
count++;
System.out.println("客户端的数量"+count);
InetAddress address=socket.getInetAddress();
System.out.println("当前客户端的IP地址是"+address);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
启动线程监听多个客户端
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.Socket;
public class ServerThread extends Thread {
Socket socket=null;
public ServerThread(Socket s){
this.socket=s;
}
//线程执行的操作,响应客户端的请求
public void run(){
//字节流 ,字符流,缓存流 初始化
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
try {
is = null;
isr = null;
br = null;
//讲接受的socket 放在字节流中
is=socket.getInputStream();
//讲字节流转为字符流
isr=new InputStreamReader(is);
//讲字节流转为 缓存流
br=new BufferedReader(isr);
String info=null;
while((info=br.readLine())!=null){
System.out.print("客户端说"+info);
}
socket.shutdownInput();
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("我是服务器欢迎你!");
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(pw!=null)
pw.close();
if(os!=null)
os.close();
if(br!=null)
br.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
client 端实现
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.Socket;
import java.net.UnknownHostException;
public class Cilent {
public static void main(String args[]) {
try {
for (int i = 0; i < 5; i++) {
Socket c = new Socket("localhost", 8888);
// 输出流
OutputStream os = c.getOutputStream();
// 打印流
PrintWriter pw = new PrintWriter(os);
pw.write("用户名 admin,密码:password");
pw.flush();
c.shutdownOutput();
// 讲接受的socket 放在字节流中
InputStream is = c.getInputStream();
// 讲字节流转为字符流
InputStreamReader isr = new InputStreamReader(is);
// 讲字节流转为 缓存流
BufferedReader br = new BufferedReader(isr);
String info;
while ((info = br.readLine()) != null) {
System.out.println("服务器端:" + info);
}
br.close();
isr.close();
is.close();
pw.close();
os.close();
c.close();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}