#java #android #sockets
#java #Android #сокеты
Вопрос:
У меня запущен java-сервер и клиент Android, который подключается к нему. Я могу успешно отправлять и получать данные из первого действия Android.
Что я хочу сделать, так это то, что когда я нажимаю кнопку входа в систему (которая работает), я хочу закрыть соединение в одном действии (домашняя страница), остановить сервер, перезапустить сервер и открыть новое соединение на перенаправленной странице.
Когда я закрываю клиентское соединение (и перезапускаю сервер) и перезапускаю клиент на следующей странице, что-то должно быть не так, потому что мой сервер перезагружается, но запускается второе действие Android и подключается к серверу, но никогда не принимает и не получает потоки ввода-вывода. Я никогда не получаю подтверждения потоков ввода-вывода.
Может быть, я создаю сокет только один раз на своем сервере??
Сервер:
public static void main(String[] args)
{
SASSServer s = new SASSServer();
}
public SASSServer()
{
try {
BuildUI();
setTitle("SASS Server");
pack();
setVisible(true);
} catch (IOException ex) {
Logger.getLogger(SASSServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void BuildUI() throws IOException
{
// create keypad
JPanel p = new JPanel();
/*
enterField = new JTextField();
enterField.setEnabled(true);
enterField.addActionListener(
new ActionListener() {
// send message to client
public void actionPerformed(ActionEvent event) {
sendData(event.getActionCommand());
}
}
);
p.add(enterField);*/
p.setLayout(new GridLayout(4, 1, 2, 2));
ConnectServer = new JButton("Connect to server");
p.add(ConnectServer);
ConnectDatabase = new JButton("Connect to database");
p.add(ConnectDatabase);
CloseServer = new JButton("Close Server");
p.add(CloseServer);
add("Center", p);
addWindowListener(this);
addWindowFocusListener(this);
addWindowStateListener(this);
ConnectServer.addActionListener(this);
ConnectDatabase.addActionListener(this);
CloseServer.addActionListener(this);
Create a ServerSocket.
server = new ServerSocket(5001, 100);
}
public void runServer() throws Exception
{
try
{
while (true) {
// Step 2: Wait for a connection.
waitForConnection();
// Step 3: Get input and output streams.
getStreams();
// Step 4: Process connection.
processConnections();
// Step 5: Close connection.
closeConnection();
counter;
}
}
catch (EOFException eofException)
{
System.out.println("Client terminated connection");
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
// wait for connectionto arrive, then display connection info
private void waitForConnection() throws IOException
{
System.out.println("Waiting for connectionn");
connection = server.accept();
System.out.println("Connection " counter " received from: "
connection.getInetAddress().getHostName());
}
// get streams to send and receive data
private void getStreams() throws IOException
{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("nGot I/O streamsn");
}
private void sendData(String message)
{
try
{
output.writeObject(message);
output.flush();
System.out.println("nCLIENT>>>" message);
}
catch (IOException ioException)
{
System.out.println("nError writing object");
}
}
// close streams and socket
private void closeConnection() throws IOException
{
try
{
System.out.println("nUser terminated connection");
output.close();
input.close();
connection.close();
}
catch (Exception ex)
{
Logger.getLogger(SASSServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
// process connection with client
public void processConnections() throws Exception
{
String message = "SERVER>>> Connection successful";
output.writeObject(message);
output.flush();
do
{
try
{
message = (String) input.readObject();
if (message.equals("TERMINATE"))
{
closeConnection();
runServer();
}
else
{
System.out.println("XML string being created into document : " message);
Document d = CreateDocumentFromString(message);
String xmlname = "ServerData.xml";
x.saveDoc(d, xmlname);
processXML(xmlname);
System.out.println("Document " xmlname " has been created" );
System.out.println("n Message: " message);
}
}
catch (ClassNotFoundException classNotFoundException)
{
System.out.println("nUnknown object type received");
}
}
while (!message.equals("CLIENT>>> TERMINATE"));
}
Клиент:
// the thread that will be communicating with the server
public class ServerConnection extends Thread
{
// the I/O streams that will be receiving/sending data from/to the
// server
private ObjectOutputStream output;
private ObjectInputStream input;
private Socket client;
@Override
public void run()
{
try
{
// Step 1: Create a Socket to make connection
connectToServer();
// Step 2: Get the input and output streams
getStreams();
// Step 3: Process connection
processConnection();
// Step 4: Close connection
//closeConnection();
}
catch (IOException e)
{
Log.e("CONNECTION", e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void connectToServer() throws IOException {
addMessage("Attempting connectionn");
client = new Socket(##IP Address##, 5001);
addMessage("Connected to: " client.getInetAddress().getHostName());
}
private void getStreams() throws IOException
{
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());
connection.sendData("You got the streams");
addMessage("Got I/O streams");
}
private void processXML(String m) throws Exception
{
addMessage(m);
}
public void processConnection() throws Exception
{
do
{
try
{
message = (String) input.readObject();
addMessage(message);
processXML(message);
}
catch (ClassNotFoundException classNotFoundException)
{
addMessage("ERROR: Unknown object type received");
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (!message.equals("SERVER>>> TERMINATE"));
}
private void sendData(String message) {
try {
output.writeObject(message);
output.flush();
addMessage("CLIENT>>>" message);
} catch (IOException ioException) {
addMessage("ERROR: Error writing object");
}
}
private void closeConnection() throws IOException {
addMessage("Closing connection");
output.close();
input.close();
client.close();
}
}
Манифест:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example02"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="LoginActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name="AddTutor"
android:label="@string/title_activity_add_tutor" >
</activity>
<activity
android:name="InsertTutor"
android:label="@string/title_activity_insert_tutor" >
</activity>
</application>
</manifest>
Я запускаю один и тот же клиентский код в обоих действиях Android, но все же второе действие просто никогда не получает мои потоки.
Пожалуйста, скажите мне, где я ошибаюсь, потому что я срываю волосы с разочарования.
Ответ №1:
Я был очень глуп. Я забыл добавить права доступа к Интернету в свой манифест. Для всех, у кого есть эта проблема, я решил ее.