Автор: Пользователь скрыл имя, 17 Декабря 2012 в 23:56, диссертация
Постановка задачи: Создать клиент-серверное приложение для обмена сообщениями в реальном времени.
Детальное описание: Клиентская часть должна быть реализована в графическом варианте. После запуска клиент пытается установить соединение с сервером, получает список всех доступных для общения пользователей, которым может отправлять/получать сообщения. Необходимо оповещать клиента об изменение в доступном списке контактов.
Скрипт создания базы данных.
CREATE TABLE "USERS"
( "LOGIN" VARCHAR2(500) NOT NULL ENABLE,
"ADDRESS" VARCHAR2(100) NOT NULL ENABLE,
CONSTRAINT "USERS_PK" PRIMARY KEY ("LOGIN") ENABLE
)
CREATE table "LOGS" (
"FROM_USER" VARCHAR2(500) NOT NULL,
"TO_USER" VARCHAR2(500) NOT NULL,
"TEXT" VARCHAR2(4000) NOT NULL,
"MESSAGE_DATE" DATE NOT NULL
Программный код системы обмена мгновенными сообщениями.
Сервер:
package ua.edu.sumdu.lab2.Server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class, extends Thread
* @author Eugene
*
*/
public class Client extends Thread implements ClientInterface {
private String clientId;
private Socket client = null;
private String host;
private Socket userSocket = null;
/**
* Constructor of the class
* @param id
* @param client
*/
public Client(String id, Socket client, String host, Socket userSocket) {
this.clientId = id;
this.client = client;
this.host = host;
this.userSocket = userSocket;
this.registerClient();
this.start();
}
/**
* Read input message from client socket
* @return
* @throws IOException
*/
public String inputMessage() throws IOException {
BufferedReader input = new BufferedReader(
new InputStreamReader(client.
return input.readLine();
}
/**
* Starting thread
*/
public void run() {
while(true) {
try {
String message = this.inputMessage();
ProtocolInterface protocol = new Protocol();
try {
protocol.parseMsg(message);
} catch (Exception e) {
this.client.close();
ClientList.remove(this.
}
SenderInterface sender = new Sender(protocol.getAuthor(), protocol.getDestination(), protocol.getText());
sender.outputMessage(message);
} catch (IOException e) {
break;
}
}
}
@Override
public Socket getConnection() {
return this.client;
}
@Override
public String getClientId() {
return this.clientId;
}
@Override
public void registerClient() {
try {
DBConnectionInterface connection = new DBConnection();
DBKitInterface reg = new DBKit(connection.getConnection
reg.addUser(this.clientId, this.host);
} catch (Exception e) {
try {
client.close();
ClientList.remove(this.
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public Socket getUserSocket() {
return this.userSocket;
}
@Override
public void closeConnection() {
try {
this.userSocket.close();
this.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import java.net.Socket;
/**
* Client Interface
* @author Eugene
*
*/
public interface ClientInterface {
/**
* Read input message from client socket
* @return
* @throws IOException
*/
public String inputMessage() throws IOException;
/**
* Getting client id
* @return id
*/
public String getClientId();
/**
* Get current client connection
* @return connection
*/
public Socket getConnection();
/**
* Register client to database
* @throws IOException
*/
public void registerClient();
/**
* Get user socket connection
* @return connection socket
*/
public Socket getUserSocket();
/**
* Close all connections
*/
public void closeConnection();
}
package ua.edu.sumdu.lab2.Server;
import java.util.LinkedList;
import java.util.List;
public class ClientList {
private static List <ClientInterface> clientList = new LinkedList <ClientInterface> ();
/**
* Add new client into the list
* @param client
*/
public static void add(ClientInterface client) {
clientList.add(client);
}
/**
* Get client with some index
* @param index
* @return client
*/
public static ClientInterface get(int index) {
return clientList.get(index);
}
/**
* Remove client with some index
* @param id
*/
public static void remove(String id) {
for(int i = 0; i < clientList.size(); i++) {
ClientInterface client = clientList.get(i);
if(client.getClientId().
clientList.remove(i);
}
}
/**
* Get size of client list
* @return size
*/
public static int size() {
return clientList.size();
}
/**
* Convert clients to the string and parse in xml
* @return
*/
public static String toXML() {
StringBuilder builder = new StringBuilder();
builder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
builder.append("<users>");
for(int i = 0; i < clientList.size(); i++) {
ClientInterface client = clientList.get(i);
builder.append("<user>");
builder.append(client.
builder.append("</user>");
}
builder.append("</users>");
return builder.toString();
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import java.net.ServerSocket;
import javax.xml.parsers.
import javax.xml.parsers.
import javax.xml.parsers.
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Connector implements ConnectorInterface {
private static final int PORT = 8085;
private int port;
@Override
public ServerSocket getConnection(String serverData) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf
= DocumentBuilderFactory.
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.parse(serverData);
String portStr = null;
NodeList items = doc.getDocumentElement().
for(int j = 0; j < items.getLength(); j++) {
NodeList list = items.item(j).getChildNodes();
for(int i = 0; i < list.getLength(); i++) {
if(items.item(j).getNodeName()
portStr = list.item(i).getNodeValue();
}
}
try {
this.port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
this.port = PORT;
}
ServerSocket server = new ServerSocket(this.port);
return server;
}
@Override
public int getPort() {
return port;
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import java.net.ServerSocket;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public interface ConnectorInterface {
/**
* Get connection from the xml file. If exception - using some default port
* @return connection
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public ServerSocket getConnection(String serverData)
throws ParserConfigurationException, SAXException, IOException;
/**
* Get information about server port
* @return port
*/
public int getPort();
}
package ua.edu.sumdu.lab2.Server;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Locale;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class DBConnection implements DBConnectionInterface {
private Connection connection;
private String sourceName;
private static final String CONFIGURATION = "dataSource.xml";
public DBConnection() throws Exception {
DocumentBuilderFactory dbf
= DocumentBuilderFactory.
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.parse(CONFIGURATION
NodeList items = doc.getDocumentElement().
String url = null;
String user = null;
String password = null;
String driver = null;
for(int j = 0; j < items.getLength(); j++) {
NodeList list = items.item(j).getChildNodes();
for(int i = 0; i < list.getLength(); i++) {
if(items.item(j).getNodeName()
this.sourceName = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
url = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
driver = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
user = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
password = list.item(i).getNodeValue();
}
}
Class.forName(driver);
Locale.setDefault(Locale.
connection = DriverManager.getConnection(
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public String getSourceName() {
return this.sourceName;
}
}
package ua.edu.sumdu.lab2.Server;
import java.sql.Connection;
/**
* DB Connection container
* @author Eugene
*
*/
public interface DBConnectionInterface {
/**
* Get DB connection
* @return connection
*/
public Connection getConnection();
/**
* Get database source name
* @return source name
*/
public String getSourceName();
}
package ua.edu.sumdu.lab2.Server;
import java.sql.*;
public class DBKit implements DBKitInterface {
private static final String ADD_LOG = "INSERT INTO Logs (FROM_USER, TO_USER, TEXT, MESSAGE_DATE) VALUES (?, ?, ?, SYSTIMESTAMP)";
private static final String ADD_USER = "INSERT INTO Users (Login, Address) VALUES (?, ?)";
private static final String FIND_USER = "SELECT Login, Address FROM Users WHERE Login = ?";
private static final String UPDATE_HOST = "UPDATE Users SET address = ? WHERE login = ?";
private Connection connection;
public DBKit(Connection connection) {
this.connection = connection;
}
@Override
public void addUser(String user, String host) throws Exception {
PreparedStatement statement = null;
if(!this.findUser(user)) {
try {
statement = this.connection.
statement.setString(1, user);
statement.setString(2, host);
statement.execute();
} finally {
statement.close();
}
}
else {
this.updateHost(user, host);
}
}
@Override
public boolean findUser(String user) throws Exception {
PreparedStatement statement = null;
try {
statement = this.connection.
statement.setString(1, user);
ResultSet result = statement.executeQuery();
if(result.next())
return true;
} finally {
statement.close();
}
return false;
}
@Override
public void updateHost(String user, String host) throws Exception {
PreparedStatement statement = null;
try {
statement = this.connection.
statement.setString(1, host);
statement.setString(2, user);
statement.execute();
} finally {
statement.close();
}
}
@Override
public void setLogs(String from, String to, String text) throws Exception {
PreparedStatement statement = null;
try {
statement = this.connection.
statement.setString(1, from);
statement.setString(2, to);
statement.setString(3, text);
statement.execute();
} finally {
statement.close();
}
}
}
package ua.edu.sumdu.lab2.Server;
/**
* Working with database
* @author Eugene
*
*/
public interface DBKitInterface {
/**
* Add user into the base
* @throws Exception
*/
public void addUser(String user, String host) throws Exception;
/**
* Find some user into the base
* @param user
* @param host
* @return true if user was found
* @throws Exception
*/
public boolean findUser(String user) throws Exception;
/**
* Update some user host
* @param user
* @param host
* @throws Exception
*/
public void updateHost(String user, String host) throws Exception;
/**
* To place logs into the DB
* @param from
* @param to
* @param text
* @throws Exception
*/
public void setLogs(String from, String to, String text) throws Exception;
}
package ua.edu.sumdu.lab2.Server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.
import javax.xml.parsers.
import javax.xml.parsers.
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Protocol implements ProtocolInterface {
private String text;
private String from;
private String to;
@Override
public void parseMsg(String msg)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf
= DocumentBuilderFactory.
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.parse(new
ByteArrayInputStream(msg.
NodeList items = doc.getDocumentElement().
for(int j = 0; j < items.getLength(); j++) {
NodeList list = items.item(j).getChildNodes();
for(int i = 0; i < list.getLength(); i++) {
if(items.item(j).getNodeName()
from = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
to = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
text = list.item(i).getNodeValue();
}
}
}
@Override
public String createMsg() {
StringBuffer xmlText = new StringBuffer();
xmlText.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
xmlText.append("<message>");
xmlText.append("<from>");
xmlText.append(this.getAuthor(
xmlText.append("</from>");
xmlText.append("<to>");
xmlText.append(this.
xmlText.append("</to>");
xmlText.append("<text>");
xmlText.append(this.getText())
xmlText.append("</text>");
xmlText.append("</message>");
return xmlText.toString();
}
@Override
public void setAuthor(String author) {
this.from = author;
}
@Override
public void setDestination(String to) {
this.to = to;
}
@Override
public void setText(String text) {
this.text = text;
}
@Override
public String getAuthor() {
return from;
}
@Override
public String getText() {
return text;
}
@Override
public String getDestination() {
return to;
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public interface ProtocolInterface {
/**
* Parse message using String message with xml tags
* @param msg
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public void parseMsg(String msg)
throws SAXException, IOException, ParserConfigurationException;
/**
* Create xml structure message, with from, to and text tags
* @return xml message
*/
public String createMsg();
/**
* Set author of the message
* @param author
*/
public void setAuthor(String author);
/**
* User, to whom send message
* @param to
*/
public void setDestination(String to);
/**
* Set text message
* @param text
*/
public void setText(String text);
/**
* Get author name
* @return author
*/
public String getAuthor();
/**
* Get text message
* @return text
*/
public String getText();
/**
* Get author of the message
* @return author
*/
public String getDestination();
}
package ua.edu.sumdu.lab2.Server;
public class Run {
private static final String STARTED = "Server started";
private static final String ERROR = "Error starting server. Maybe port already used";
private static final String SERVER_DATA = "server.xml";
/**
* Print some message to the screen
* @param message
*/
private static void printMessage(String message) {
System.out.println(message);
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ServerInterface server = new Server();
try {
printMessage(STARTED);
server.start(SERVER_DATA);
} catch (Exception e) {
printMessage(ERROR);
}
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Sender extends Thread implements SenderInterface {
String destination;
String author;
String text;
public Sender(String author, String destination, String text) {
this.destination = destination;
this.author = author;
this.text = text;
}
@Override
public void outputMessage(String message) throws IOException {
for(int i = 0; i < ClientList.size(); i++)
{
ClientInterface client = ClientList.get(i);
if(client.getClientId().
PrintWriter output = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(client.
output.println(message);
try {
DBConnectionInterface connection = new DBConnection();
DBKitInterface logs = new DBKit(connection.
logs.setLogs(this.author, this.destination, this.text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
/**
* Sending messages
* @author Eugene
*
*/
public interface SenderInterface {
/**
* Send some message to the client
* @param message
* @throws IOException
*/
public void outputMessage(String message) throws IOException;
}
package ua.edu.sumdu.lab2.Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
public class Server implements ServerInterface{
private boolean status = false;
@Override
public void start(String serverData)
throws IOException, ParserConfigurationException, SAXException {
ConnectorInterface connector = new Connector();
ServerSocket server = connector.getConnection(
ServerSocket userServer =
new ServerSocket((server.
try {
this.setStatus(true);
while(true) {
Socket clientSocket = server.accept();
Socket userSocket = userServer.accept();
String clientName = this.getParam(clientSocket);
String host = this.getParam(clientSocket);
ClientInterface client = new Client(clientName, clientSocket, host, userSocket);
ClientList.add(client);
UserSenderInterface sender = new UserSender();
}
} finally {
server.close();
this.setStatus(false);
}
}
@Override
public String getParam(Socket clientSocket) throws IOException {
BufferedReader input = new BufferedReader(
new InputStreamReader(
Информация о работе Создание системы обмена мгновенными сообщениями