Доброго времени суток.Пытаюсь сделать простое клиент-серверное приложение. Клиент - приложение на Android устройстве. Сервер - Приложение на Java на моём компьютере. Много смотрел теории и написал следующий код.
По идее я включаю сервер на компьютере, затем захожу в приложение на Android устройстве, ввожу в поле ввода слово любое,по нажатию кнопки оно должно отправляться на сервер. Сервер в свою очередь должен принять его , дописать фразу к полученному сообщению "Hello From Server" и вернуть его обратно клиенту.
У меня сервер запускается нормально , а когда пытаюсь отправить на сервер ,по нажатию кнопки происходит ошибка и из приложения просто выкидывает.
Клиент:
Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
| package com.example.myclient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
static private ObjectOutputStream output;
static private ObjectInputStream input;
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
Context c;
Button send;
TextView tv1;
static DataOutputStream dataOutputStream= null;
DataInputStream dataInputStream = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText);
tv1 = (TextView)findViewById(R.id.textView1);
c=this;
send=(Button)findViewById(R.id.buttonSend);
send.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.buttonSend:
Networking n =new Networking();
n.execute();
break;
}
}
public class Networking extends AsyncTask{
@Override
protected Object doInBackground(Object[] arg0) {
toast("dasdsadasdada");
messsage = textField.getText().toString();
Socket client =null;
//textField.setText("");
try {
client = new Socket("188.237.142.66", 6103);
client.setKeepAlive(true);
client.setSoTimeout(1000);
dataOutputStream = new DataOutputStream(client.getOutputStream());
dataInputStream = new DataInputStream(client.getInputStream());
/*
input = new ObjectInputStream(client.getInputStream());
output = new ObjectOutputStream(client.getOutputStream());
*/
dataOutputStream.writeUTF(messsage);
toast((String)dataInputStream.readUTF());
} catch (UnknownHostException e) {
e.printStackTrace();
toast("Got an UnknownHostException: " + e.getMessage());
} catch (IOException e) {
tv1.setText("Got an IOException: " + e.getMessage());
toast("Got an IOException: " + e.getMessage());
}
return null;
}
}
private void toast(final String s){
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable(){
@Override
public void run() {
Toast.makeText(c, s, Toast.LENGTH_SHORT).show();
}
});
}
} |
|
Android Минифест файл для Клиента.
XML |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE">
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myclient.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>
</application>
</manifest> |
|
Серверная часть:
Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
| import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(6103,10);
System.out.println("Listening :6102");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
System.out.println("Сервер готов работать.");
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("socket" + socket);
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello from Server!" + dataInputStream.readUTF());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} |
|
Просмотрел много статей на форуме, делал по примеру,вроде бы учёл все ошибки,но Увы не выходит. Буду очень признателен за помощь.