THE THIRTY-SEVENTH DAY

    今天星期六,参加培训的第三十六天,与往常一样,还是上自习,至于到底,做了什么,实在是忘记的差不多了,然后就把自己写的代码用着两天的日记贴出来好了,就这样,然后就是代码时间了。

    服务端代码:

maincotrol:

package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.management.ObjectInstance;
import javax.swing.JOptionPane;

import client.RegisterControl.HandleClient;
import dao.UserDao;
import dao.UserUserDao;
import entity.User;

public class MainControl {
	private ServerSocket serverSocket;
	private ServerSocket chatServerSocket;
	private ServerSocket addServerSocket;
//	DataInputStream inputFromClient;
//	DataOutputStream outputToClient;
//	ObjectInputStream objectFromClient;
//	ObjectOutputStream objectToClient;
//	ObjectInputStream objectFromClientChat;
//	ObjectOutputStream objectToClientChat;
	ObjectInputStream objectFromClientAdd;//处理客户端addFriendview的请求
	ObjectOutputStream objectToClientAdd;
	UserDao userDao = new UserDao();
	UserUserDao userUserDao = new UserUserDao();
	HashMap<String, Socket> accountSocketMap = new HashMap<>();//mainview socket与account
    HashMap<String, Socket> chatSocketMap = new HashMap<>();//chatview chatsocket与account
    HashMap<Socket, ObjectOutputStream> socketStreamMap = new HashMap<>();//mainview socket与outputStream
    HashMap<Socket, ObjectOutputStream> socketStreamChatMap = new HashMap<>();//chatview chatsocket与outputStreamchat
	public MainControl() {
		// TODO Auto-generated constructor stub
		try {

			serverSocket = new ServerSocket(7000);
			chatServerSocket = new ServerSocket(9000);
			addServerSocket = new ServerSocket(6000);
			ExecutorService executorService = Executors.newCachedThreadPool();
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					while (true) {
						try {
							Socket socket = serverSocket.accept();
							ObjectOutputStream objectToClient = new ObjectOutputStream(socket.getOutputStream());
							ObjectInputStream objectFromClient = new ObjectInputStream(socket.getInputStream());
							String account = objectFromClient.readUTF();
							accountSocketMap.put(account, socket);
							socketStreamMap.put(socket, objectToClient);
							HandleClient MainTask = new HandleClient(socket, account,
									objectFromClient,objectToClient);
							new Thread(MainTask).start();
						} catch (IOException e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
				}
			});
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						while (true) {
							Socket chatSocket = chatServerSocket.accept();
							ObjectOutputStream objectToClientChat = new ObjectOutputStream(chatSocket.getOutputStream());
							ObjectInputStream objectFromClientChat = new ObjectInputStream(chatSocket.getInputStream());
							String account=objectFromClientChat.readUTF();
							chatSocketMap.put(account, chatSocket);
							JOptionPane.showMessageDialog(null, "chatSocket"+chatSocket);
							socketStreamChatMap.put(chatSocket, objectToClientChat);
							HandleChat handleChat = new HandleChat(chatSocket,account,
									objectFromClientChat,objectToClientChat);
							new Thread(handleChat).start();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						while (true) {
							Socket addSocket = addServerSocket.accept();
							objectToClientAdd = new ObjectOutputStream(addSocket.getOutputStream());
							objectFromClientAdd = new ObjectInputStream(addSocket.getInputStream());
							HandleAdd handleAdd = new HandleAdd(addSocket);
							new Thread(handleAdd).start();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});

			// inputFromClient= new DataInputStream(socket.getInputStream());
			// outputToClient = new DataOutputStream(socket.getOutputStream());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class HandleChat implements Runnable {
		private Socket socket;
        private String account;
        private ObjectInputStream objectFromClientChat;
        private ObjectOutputStream objectToClientChat;
		public HandleChat(Socket socket,String account,
				ObjectInputStream objectFromClientChat,ObjectOutputStream objectToClientChat) {
			// TODO Auto-generated constructor stub
			this.socket = socket;
			this.account=account;
			this.objectFromClientChat=objectFromClientChat;
			this.objectToClientChat=objectToClientChat;
		}

		@Override
		public synchronized void run() {
			// TODO Auto-generated method stub
           
		   while(true) {
			try {
				try {
				String option = objectFromClientChat.readUTF();
				
				System.out.println(option);
				if (option.equals("getUser")) {
					// String code=SmsDemo.sendSms(str.substring(4));
					System.out.println("aaa");
					String friendAccount = objectFromClientChat.readUTF();
					User user = userDao.getUserByAccount(friendAccount);
					objectToClientChat.writeObject(user);
					objectToClientChat.flush();
					objectToClientChat.flush();
					continue;
				}
				if(option.equals("chat")) {
					String friendAccount = objectFromClientChat.readUTF();
					String text = objectFromClientChat.readUTF();
					if(accountSocketMap.containsKey(friendAccount)) {
						//如果朋友在线
						if(chatSocketMap.containsKey(friendAccount)) {
							//如果朋友自己聊天对话框存在
							JOptionPane.showMessageDialog(null, friendAccount+"朋友框存在");
							Socket chatSocket = chatSocketMap.get(friendAccount);
							JOptionPane.showMessageDialog(null, friendAccount);
							ObjectOutputStream ooChat = socketStreamChatMap.get(chatSocket);
							//从map集合获得朋友chatsocket
							ooChat.writeUTF(text);
							ooChat.flush();
						}else {
						Socket socket = accountSocketMap.get(friendAccount);
						//获得朋友mainview socket 向mainview发送数据,让其处理弹出与自己的聊天框,并将这一次消息显示在上面
					ObjectOutputStream ooMian = socketStreamMap.get(socket);
					ooMian.writeUTF("main");
					ooMian.flush();
					ooMian.writeUTF(account);
					ooMian.flush();
                    ooMian.writeUTF(text);
                    ooMian.flush();
	
					}     
					}
				}
				}catch (EOFException e) {//客户端聊天框关闭,从两个map 中删除其对应的数据
					socketStreamChatMap.remove(socket);
					chatSocketMap.remove(account);
				    break;
//					chatSocketMap.remove(account);
//					socket.close();
//					break;
				}
			} 
			catch (IOException e) {
				// TODO Auto-generated catch block
				try {
//				this.objectFromClientChat.close();
//				this.objectToClientChat.close();
					this.socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		   }
		}

	}
	class HandleAdd implements Runnable {
		private Socket socket;

		public HandleAdd(Socket socket) {
			// TODO Auto-generated constructor stub
			this.socket = socket;
		}

		@Override
		public synchronized void run() {
			// TODO Auto-generated method stub
			try {
				// inputFromClient = new DataInputStream(socket.getInputStream());
				// outputToClient = new DataOutputStream(socket.getOutputStream());
				while (true) {
					try {
						String option = objectFromClientAdd.readUTF();
						System.out.println(option);
						if (option.equals("getUser")) {
							// String code=SmsDemo.sendSms(str.substring(4));
							System.out.println("aaa");
							String account = objectFromClientAdd.readUTF();
							User user = userDao.getUserByAccount(account);
							objectToClientAdd.writeObject(user);
							objectToClientAdd.flush();
							objectToClientAdd.flush();
							continue;
						}
						if (option.equals("isFriendExists")) {
							String account1 = objectFromClientAdd.readUTF();
							String account2 = objectFromClientAdd.readUTF();
							objectToClientAdd.writeBoolean(userUserDao.isFriendExists(account1, account2));
							objectToClientAdd.flush();
//							objectToClientAdd.flush();
						}
						if (option.equals("addFriend")) {
							String account1 = objectFromClientAdd.readUTF();
							String account2 = objectFromClientAdd.readUTF();
							objectToClientAdd.writeBoolean(userUserDao.addFriend(account1, account2));
							objectToClientAdd.flush();
						}
					} catch (EOFException e) {
//						socket.close();
						e.printStackTrace();
						break;
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				try {
					e.printStackTrace();
					this.socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
			// catch (ClientException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		}

	}
	class HandleClient implements Runnable {
		private Socket socket;
		private String account;
        private ObjectInputStream objectFromClient;
        private ObjectOutputStream objectToClient;
		public HandleClient(Socket socket, String account,
				ObjectInputStream objectFromClient,ObjectOutputStream objectToClient) {
			// TODO Auto-generated constructor stub
			this.socket = socket;
			this.account = account;
			this.objectFromClient=objectFromClient;
			this.objectToClient=objectToClient;
		}

		@Override
		public synchronized void run() {
			// TODO Auto-generated method stub
			try {
				// inputFromClient = new DataInputStream(socket.getInputStream());
				// outputToClient = new DataOutputStream(socket.getOutputStream());
				while (true) {
					try {
						String option = objectFromClient.readUTF();
						System.out.println(option);
						if (option.equals("getUser")) {
							// String code=SmsDemo.sendSms(str.substring(4));
							System.out.println("aaa");
							String account = objectFromClient.readUTF();
							User user = userDao.getUserByAccount(account);
							Socket socket = accountSocketMap.get(account);
							ObjectOutputStream ooMian = socketStreamMap.get(socket);
							//用自己的objecttoclient也可以
							ooMian.writeObject(user);
							ooMian.flush();
							ooMian.flush();
							continue;
						}
						// System.out.println("bbb");
						if (option.equals("getUserList")) {
							String account = objectFromClient.readUTF();
							System.out.println(account);
							List<User> userList = userDao.getAllFriend(account);
							// System.out.println(userList.size()+"----------");
							Socket socket = accountSocketMap.get(account);
							ObjectOutputStream ooMian = socketStreamMap.get(socket);
							//同上
							ooMian.writeUTF("add");
							ooMian.flush();
							ooMian.writeObject(userList);
							ooMian.flush();
							ooMian.flush();
							continue;
						}
						if (option.equals("isFriendExists")) {
							String account1 = objectFromClient.readUTF();
							String account2 = objectFromClient.readUTF();
							objectToClient.writeBoolean(userUserDao.isFriendExists(account1, account2));
							objectToClient.flush();
							objectToClient.flush();
						}
						if (option.equals("addFriend")) {
							String account1 = objectFromClient.readUTF();
							String account2 = objectFromClient.readUTF();
							objectToClient.writeBoolean(userUserDao.addFriend(account1, account2));
							objectToClient.flush();
						}
					} catch (EOFException e) {
						e.printStackTrace();
						socketStreamMap.remove(socket);
						accountSocketMap.remove(account);
						break;
//						break;
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
			      e.printStackTrace();
				try {
//					inputFromClient.close();
//					objectFromClient.close();
					
					
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
			// catch (ClientException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		}

	}

	public static void main(String[] args) {
		MainControl mainControl = new MainControl();
	}
}

resgistercontrol,它与logincontrol合并了

package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JOptionPane;

import org.junit.jupiter.api.Test;

import com.aliyuncs.exceptions.ClientException;

import dao.UserDao;
import util.AccountUtil;
import util.SmsDemo;

public class RegisterControl {
    private ServerSocket serverSocket;
    DataInputStream inputFromClient; 
	DataOutputStream outputToClient;
	UserDao userDao = new UserDao();
//	List<HandleClient> handList = new ArrayList<>();
	ExecutorService executorService = Executors.newCachedThreadPool();
    public RegisterControl() {
		// TODO Auto-generated constructor stub
	    try {
			serverSocket=new ServerSocket(8000);			
			while(true) {
				Socket socket = serverSocket.accept();
				HandleClient handleClient = new HandleClient(socket);
//				handList.add(handleClient);
//				Thread thread = new Thread(handleClient);
//				executorService.execute(thread);
				executorService.execute(handleClient);            
			}
//			inputFromClient= new DataInputStream(socket.getInputStream());
//			outputToClient = new DataOutputStream(socket.getOutputStream());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	
    class HandleClient implements Runnable{
        private Socket socket;
        private String account;
        public HandleClient(Socket socket) {
			// TODO Auto-generated constructor stub
		    this.socket=socket;
        }
		@Override
		public synchronized void run() {
			// TODO Auto-generated method stub
				try {
					inputFromClient= new DataInputStream(socket.getInputStream());
					outputToClient = new DataOutputStream(socket.getOutputStream());
					while(true) {
						try {
					       String str = inputFromClient.readUTF();
					if(str.startsWith("code")) {
//						String code=SmsDemo.sendSms(str.substring(4));
						String code ="123456";
						outputToClient.writeUTF(code);
						outputToClient.flush();
					}
					if(str.startsWith("account")) {
						String account = AccountUtil.getAccount();
						String user[] = str.split(",");
						if(userDao.insertUser(user[1], user[2], user[3],account)==1) {
							outputToClient.writeBoolean(true);
		                    outputToClient.writeUTF("注册成功!账户为:"+account);
		                    outputToClient.flush();
						} else {
							outputToClient.writeBoolean(false);
							outputToClient.writeUTF("注册失败");
							outputToClient.flush();
						}
					}
					if(str.startsWith("password")) {
						System.out.println("登录");
						String[] accountAndPassword=str.split(",");
						if(userDao.isAccountExists(accountAndPassword[1], accountAndPassword[2])) {
							this.account=accountAndPassword[1];
							outputToClient.writeBoolean(true);
						} else {
							outputToClient.writeBoolean(false);
						}
					}
					} catch (EOFException e){
						break;	
				}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				catch (ClientException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
		}
		
    }	
public static void main(String[] args) {
    RegisterControl rc = new RegisterControl();
}

}

severcontrol:

package client;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerControl {
    public static void main(String[] args) {
    	ExecutorService executor = Executors.newCachedThreadPool();
    	executor.execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				RegisterControl registerControl = new RegisterControl();
			}
		});
		executor.execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				MainControl mainControl = new MainControl();
			}
		});
		
	}
}

突然有一些东西懒的贴了,然后就随便贴我想贴的吧:

accountutil:

package util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AccountUtil {
    private static int account;
    private static File file = new File("a.dat");
//    static {
//    	DataOutputStream dos;
//		try {
//			dos = new DataOutputStream(new FileOutputStream(file));
//			dos.writeInt(10000000);
//			dos.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    }
    public AccountUtil() {
		// TODO Auto-generated constructor stub
	
    }
    
    private static  void readAccount() {
        try {
    			DataInputStream dis = new DataInputStream(new  FileInputStream(file));
    			account = dis.readInt();
    			dis.close();
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    }
   private static  void changeAccount() {
    	try {
			DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
			dos.writeInt(account+1);
			dos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	public static synchronized String getAccount() {
		readAccount();
		changeAccount();
		return account+"";		
	}
    
}

jdbcutil

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JDBCUtil {
//	private static String DRIVER = "com.mysql.jdbc.Driver";
//	private static String URL = "jdbc:mysql://127.0.0.1:3306/180408work";
//	private static String USER = "root";
//	private static String PASSWORD = "lizean";

	private  final static String DRIVER;
	private  final static String URL;
	private  final static String USER;
	private  final static String PASSWORD;
	private JDBCUtil() {
 
	}

	static {
		ResourceBundle rb = ResourceBundle.getBundle("jdbc");
		DRIVER = rb.getString("driver");
		URL = rb.getString("url");
		USER = rb.getString("user");
		PASSWORD = rb.getString("pass");
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
public static void main(String[] args) {
	getConnection();
}
	public static Connection getConnection()  {
		// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		try {
			return DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static Statement getStatement()  {
		try {
			return getConnection().createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static void close(Connection conn, Statement st, ResultSet resultSet) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void close(Connection conn, Statement st) {
		try {
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
服务器端就这些吧,下篇日记再贴客户端的代码,好结束。




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aizaiee/article/details/79955715
个人分类: 培训日记
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭