Автор: Пользователь скрыл имя, 17 Декабря 2012 в 23:56, диссертация
Постановка задачи: Создать клиент-серверное приложение для обмена сообщениями в реальном времени.
Детальное описание: Клиентская часть должна быть реализована в графическом варианте. После запуска клиент пытается установить соединение с сервером, получает список всех доступных для общения пользователей, которым может отправлять/получать сообщения. Необходимо оповещать клиента об изменение в доступном списке контактов.
return input.readLine();
}
@Override
public boolean getStatus() {
return this.status;
}
@Override
public int getServerPort() {
ConnectorInterface connector = new Connector();
return connector.getPort();
}
@Override
public void setStatus(boolean status) {
this.status = status;
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import java.net.Socket;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public interface ServerInterface {
/**
* Method for starting server
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public void start(String serverData) throws IOException, ParserConfigurationException, SAXException;
/**
* Getting server status
* @return server status
*/
public boolean getStatus();
/**
* Getting server port
* @return port
*/
public int getServerPort();
/**
* Set server status
* @param status
* @return
*/
public void setStatus(boolean status);
/**
* Get parameters of the client
* @param clientSocket
* @return id
* @throws IOException
*/
public String getParam(Socket clientSocket) throws IOException;
}
package ua.edu.sumdu.lab2.Server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class UserSender extends Thread implements UserSenderInterface {
public UserSender() {
this.start();
}
@Override
public void run() {
while(true) {
for(int i = 0; i < ClientList.size(); i++) {
ClientInterface client = ClientList.get(i);
Socket userSocket = client.getUserSocket();
try {
this.sendList(ClientList.
if(this.getMessage(userSocket) == null) {
throw new Exception();
}
} catch (Exception e1) {
client.closeConnection();
ClientList.remove(client.
}
}
try {
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void sendList(String list, Socket client) throws IOException {
PrintWriter output = null;
output = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(client.
output.println(list);
}
public String getMessage(Socket client) throws IOException {
BufferedReader input = new BufferedReader(
new InputStreamReader(client.
return input.readLine();
}
}
package ua.edu.sumdu.lab2.Server;
import java.io.IOException;
import java.net.Socket;
/**
* Sending user list to client
* @author Eugene
*
*/
public interface UserSenderInterface {
/**
* Send user list to other clients
* @throws IOException
*/
public void sendList(String list, Socket client) throws IOException;
}
Клиент:
package ua.edu.sumdu.lab2.Client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
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 Socket client;
private String host;
private int port;
/**
* Constructor of the class
* @throws UnknownHostException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public Connector(String serverData)
throws UnknownHostException, IOException, SAXException, ParserConfigurationException {
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()
this.host = list.item(i).getNodeValue();
if(items.item(j).getNodeName()
portStr = list.item(i).getNodeValue();
}
}
try {
this.port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
this.port = PORT;
}
try {
client = new Socket(this.host, this.port);
} catch (Exception e) {
System.exit(1);
}
}
@Override
public Socket getConnect() {
return client;
}
}
package ua.edu.sumdu.lab2.Client;
import java.net.Socket;
/**
* Class for connecting to server and sending or getting message
* @author Eugene
*
*/
public interface ConnectorInterface {
/**
* Get connection from XML file or constants
* @return Socket
*/
public Socket getConnect();
}
package ua.edu.sumdu.lab2.Client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public class Controller implements ControllerInterface {
private Socket connection;
SenderInterface sender;
ReceiverInterface receiver;
UserList list;
@Override
public void Connect(String serverData)
throws UnknownHostException, IOException, SAXException, ParserConfigurationException {
ConnectorInterface connector = new Connector(serverData);
connection = connector.getConnect();
}
@Override
public void sending(String user) {
sender = new Sender(this.connection, user);
}
@Override
public void receiving() {
receiver = new Receiver(this.connection);
}
@Override
public void userList() {
list = new UserList(connection);
}
@Override
public void sendMessage(String message) {
sender.putMessage(message);
receiver.addOutputMessage(
}
@Override
public DefaultListModel getMessageList() {
return receiver.getMessageList();
}
}
package ua.edu.sumdu.lab2.Client;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public interface ControllerInterface {
/**
* Sending messages to the user
*/
public void sending(String user);
/**
* Receiving message from the server
*/
public void receiving();
/**
* Connect to the server
* @param serverData
* @throws UnknownHostException
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public void Connect(String serverData) throws UnknownHostException, IOException, SAXException, ParserConfigurationException;
/**
* Getting user list from the server
*/
public void userList();
/**
* Send this message to the server
* @param message
*/
public void sendMessage(String message);
/**
* Get message list
* @return DefaultListModel
*/
public DefaultListModel getMessageList();
}
package ua.edu.sumdu.lab2.Client;
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.getDestina
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.Client;
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.Client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.DefaultListModel;
import javax.xml.parsers.
import org.xml.sax.SAXException;
public class Receiver extends Thread implements ReceiverInterface {
private static final String ERROR = "Error";
private static final String WELCOME_MSG = "Welcome to our chat room";
private static final String USER_ID = "Your: ";
Socket client;
private DefaultListModel messageList;
public Receiver(Socket client) {
this.client = client;
messageList = new DefaultListModel();
messageList.addElement(
this.start();
}
@Override
public String getMessage() throws IOException {
BufferedReader input = new BufferedReader(
new InputStreamReader(client.
return input.readLine();
}
public void run() {
while(true) {
try {
ProtocolInterface protocol = new Protocol();
protocol.parseMsg(this.
this.messageList.addElement(
} catch (IOException | SAXException | ParserConfigurationException e) {
break;
}
}
}
@Override
public DefaultListModel getMessageList() {
return this.messageList;
}
@Override
public void addOutputMessage(String message) {
this.messageList.addElement(
}
}
package ua.edu.sumdu.lab2.Client;
import java.io.IOException;
import javax.swing.DefaultListModel;
public interface ReceiverInterface {
/**
* Get message from the server
* @return
* @throws IOException
*/
public String getMessage() throws IOException;
/**
* Get default list model
* @return DefaultListModel
*/
public DefaultListModel getMessageList();
/**
* Add output message to message list
* @param message
*/
public void addOutputMessage(String message);
}
package ua.edu.sumdu.lab2.Client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Sender extends Thread implements SenderInterface {
private Socket client;
private String id;
private String host;
private String message = null;
public Sender(Socket client, String id) {
this.client = client;
try {
this.sendMessage(id);
this.id = id;
InetAddress address = InetAddress.getLocalHost();
this.sendMessage(address.
this.host = address.getHostAddress();
} catch (IOException e) {
System.exit(1);
}
this.start();
}
@Override
public void sendMessage(String message) throws IOException {
PrintWriter output = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(client.
output.println(message);
}
@Override
public void run() {
while(true) {
try {
if(this.message != null) {
ProtocolInterface protocol = new Protocol();
protocol.setAuthor(this.id);
protocol.setDestination(
protocol.setText(this.message)
this.sendMessage(protocol.
this.message = null;
}
} catch (IOException e) {
this.resume();
}
}
}
@Override
public void putMessage(String message) {
this.message = message;
}
@Override
public String getLogin() {
return this.id;
}
}
package ua.edu.sumdu.lab2.Client;
import java.io.IOException;
/**
* Need for sending message to the server
* @author Eugene
*
*/
public interface SenderInterface {
/**
* Send some message to the server
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException;
/**
* Get user login
* @return login
*/
public String getLogin();
/**
* Put message into the String value
* @param message
*/
public void putMessage(String message);
}
package ua.edu.sumdu.lab2.Client;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.xml.parsers.
import org.xml.sax.SAXException;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class UserInterface {
private JFrame frmUserChat;
private JList userList;
private static ControllerInterface ctrl = new Controller();
private static final String SERVER_DATA = "server.xml";
private JTextField userName;
private JList messageList;
private JTextField textField;
private JButton sendBtn;
private JTextField destinationField;
private JButton logInBtn;
/**
* Launch the application.
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException, SAXException, ParserConfigurationException {
try {
ctrl.Connect(SERVER_DATA);
ctrl.userList();
ctrl.receiving();
} catch (IOException | SAXException
| ParserConfigurationException e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserInterface window = new UserInterface();
window.frmUserChat.setVisible(
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.*
*/
public UserInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmUserChat = new JFrame();
frmUserChat.setTitle("User Chat");
frmUserChat.setBounds(100, 100, 500, 330);
frmUserChat.
frmUserChat.getContentPane().
userList = new JList(UserList.getListModel())
userList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
destinationField.setText((
UsersGroup.setSelectedUser(
}
});
userList.setBounds(353, 44, 121, 170);
frmUserChat.getContentPane().
userName = new JTextField();
userName.setBounds(156, 11, 145, 20);
frmUserChat.getContentPane().
userName.setColumns(10);
logInBtn = new JButton("Log In");
logInBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String user = userName.getText();
if (user != null && user != "") {
ctrl.sending(user);
userList.enable(true);
messageList.enable(true);
textField.enable(true);
destinationField.enable(true);
userName.enable(false);
logInBtn.show(false);
}
}
});
logInBtn.setBounds(319, 10, 100, 23);
frmUserChat.getContentPane().
JLabel nickNameLabel = new JLabel("Nickname");
nickNameLabel.setBounds(41, 14, 80, 14);
frmUserChat.getContentPane().
messageList = new JList(ctrl.getMessageList());
messageList.setEnabled(false);
messageList.setBounds(10, 44, 337, 200);
frmUserChat.getContentPane().
textField = new JTextField();
textField.setEnabled(false);
textField.setBounds(10, 255, 333, 27);
frmUserChat.getContentPane().
textField.setColumns(10);
sendBtn = new JButton("Send");
sendBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(UsersGroup.getSelectedUser(
ctrl.sendMessage(textField.
textField.setText("");
}
});
sendBtn.setBounds(353, 255, 121, 27);
frmUserChat.getContentPane().
destinationField = new JTextField();
destinationField.setEnabled(
destinationField.setBounds(
frmUserChat.getContentPane().
destinationField.setColumns(
}
}
package ua.edu.sumdu.lab2.Client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
Информация о работе Создание системы обмена мгновенными сообщениями