1.服务器端
/**
*
*/
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.concurrent.*;
import com.mysql.jdbc.PreparedStatement;
/**
* @author linzhifeng
*
*/
public class Server{
//服务器端 需要单独编译并在命令行模式下启动测试
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost:3306/jdbc";
public static final String DBUSER = "root";
public static final String DBPASSWORD = "123456";
private static final int SERVERPORT = 54323; //服务器端口
private static List<Socket> mClientList = new ArrayList<Socket>(); //客户端连接 通过List来储存所有连接进来的客户端的Socket对象(也可用CopyOnWriteArrayList来储存)
private ExecutorService mExecutorService; //线程池 需要为每个客户端都开启一个线程
private ServerSocket mServerSocket; //ServerSocket对象
public static void main(String[] args){ //main方法 开启服务器
new Server();
}
public Server(){
try{
mServerSocket = new ServerSocket(SERVERPORT);//设置服务器端口
mExecutorService = Executors.newCachedThreadPool();//创建一个线程池
System.out.println("start...");
Socket client = null;//用来临时保存客户端连接的Socket对象
while (true){
client = mServerSocket.accept(); //接收客户连接并添加到list中
mClientList.add(client);
mExecutorService.execute(new ThreadServer(client));//开启一个客户端线程
}
}catch (IOException e){
e.printStackTrace();
}
}
static class ThreadServer implements Runnable{//每个客户端单独开启一个线程
private Socket mSocket;
private BufferedReader mBufferedReader;
private PrintWriter mPrintWriter;
private String mStrMSG;
public ThreadServer(Socket socket) throws IOException{
this.mSocket = socket;
mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mStrMSG = "user:"+this.mSocket.getInetAddress()+" come total:" + mClientList.size();
sendMessage();
}
public void run(){
try{
while ((mStrMSG = mBufferedReader.readLine()) != null){
if (mStrMSG.trim().equals("exit")){
//当一个客户端退出时
mClientList.remove(mSocket);
mBufferedReader.close();
mPrintWriter.close();
mStrMSG = "user:"+this.mSocket.getInetAddress()+" exit total:" + mClientList.size();
mSocket.close();
sendMessage();
break;
}else{
String name=mStrMSG;
mStrMSG = mSocket.getInetAddress() + ":" + mStrMSG;
Connection con = null;
try {
Class.forName(DBDRIVER);
con = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
Statement str = con.createStatement();
//String name="china";
String sql = "select id from test where country = '"+name+"' limit 0,10";
PreparedStatement st = (PreparedStatement) con.prepareStatement(sql);
java.sql.ResultSet rs=null;
rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString("id"));
mStrMSG+="|"+rs.getString("id");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendMessage();
}
}
}catch (IOException e){
e.printStackTrace();
}
}
private void sendMessage() throws IOException{//发送消息给所有客户端
System.out.println(mStrMSG);
for (Socket client : mClientList){
mPrintWriter = new PrintWriter(client.getOutputStream(), true);
mPrintWriter.println(mStrMSG);
}
}
}
}
2.客户端
/**
*
*/
package HTTP;
import java.io.*;
import java.net.Socket;
import java.util.concurrent.*;
/**
* @author linzhifeng
*
*/
public class client{//需要单独编译并在命令行模式下启动测试
private static final int PORT = 54323;
private static ExecutorService exec = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception{
new client();
}
public client(){
try{
Socket socket = new Socket("127.0.0.1", PORT);
exec.execute(new Sender(socket));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = br.readLine()) != null){
System.out.println(msg);
}
}catch (Exception e){
}
}
static class Sender implements Runnable{//客户端线程获取控制台输入消息
private Socket socket;
public Sender(Socket socket){
this.socket = socket;
}
public void run(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String msg;
while (true){
msg = br.readLine();
pw.println(msg);
if (msg.trim().equals("exit")){
pw.close();
br.close();
exec.shutdownNow();
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
3.cmd下编译运行服务器
javac -cp mysql-connector-java-5.0.8-bin.jar ./Server.java
java -cp mysql-connector-java-5.0.8-bin.jar Server