我正在制作一个通过TCP与不同活动中的java服务器连接的应用程序,所以在这里阅读最佳做法是使用Android服务。
这是我写的第一个套接字代码所以我真的不知道我在做什么
我在手机中的pc和app中使用netbeans运行服务器,但它不起作用,我的错误是什么?
ip地址是我的电脑运行服务器的私人IP,因为我在我的手机中运行应用程序
这是服务器代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket=new ServerSocket(1001);
while(true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: "+clientSentence);
capitalizedSentence = clientSentence.toUpperCase()+"\n";
outToClient.writeBytes(capitalizedSentence);
}
}
}
这是我服务的代码
package com.remedialguns.smartourist;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Locale;
public class ConnectionService extends Service{
Socket s;
PrintStream os;
public static int serverPort=1001;
public static String serverIP="192.168.1.104";
Place[] PlacesToShow = new Place[10];
private static final String TAG="com.remedialguns.smartourist";
private final IBinder myBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public void sendProfileData(String userId, String gender,int age, String Country, int[] preferences){
//send profile data to server
}
public String test(){
String test="test";
String response="";
try {
InetAddress serverAdress = InetAddress.getByName(serverIP);
s=new Socket(serverAdress, serverPort);
DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
outToClient.writeBytes(test);
response = inFromClient.readLine();
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));
//out.println(test);
}
catch (IOException e){
e.printStackTrace();
}
System.out.println(response);
return response;
}
@Override
public void onCreate(){
super.onCreate();
s=new Socket();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public Place[] getPlaces(){
//here a send a String to server and receive an object Place[]
//F̶a̶k̶e̶ ̶d̶a̶t̶a̶ Test data
PlacesToShow[0]= new Place("MUSEO","Museo Nacional Agropecuario", 0.15, 0.4, 0.12);
PlacesToShow[1]= new Place("MUSEO","Museo Arqueológico Junín",0.10, 0.78, 0.44);
PlacesToShow[2]= new Place("MUSEO","Museo Botero", 0.2, 0.8, 0.08);
PlacesToShow[3]= new Place("MUSEO","Museo de Zea", 0.3, 0.65, 0.23);
PlacesToShow[4]= new Place("MUSEO","MUSEO DEL ORO", 0.13, 0.56, 0.12);
PlacesToShow[5]= new Place("MUSEO","MUSEO DE ARTE COLONIAL", 0.3, 0.67, 0.14);
PlacesToShow[6]= new Place("MUSEO","MUSEO HISTORICO DE LA POLICIA NACIONAL", 0.34, 0.3, 0.33);
PlacesToShow[8]= new Place("MUSEO","MUSEO DE LOS NIÑOS", 0.05, 0.65, 0.03);
PlacesToShow[7]= new Place("MUSEO","Museo Nacional", 0.15, 0.4, 0.12);
PlacesToShow[9]= new Place("MUSEO","MUSEO MILITAR", 0.07, 0.5, 0.6);
return PlacesToShow;
}
public class LocalBinder extends Binder {
ConnectionService getService(){
return ConnectionService.this;
}
}
}
这是我调用测试方法的代码。 在onCreate方法中调用了methos,之前调用的方法正在工作。
package com.remedialguns.smartourist;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import com.remedialguns.smartourist.ConnectionService.LocalBinder;
import com.google.android.gms.location.places.Places;
public class ListActivity extends AppCompatActivity {
ConnectionService tcpService;
boolean isBound=false;
//Place[] PlacesToShow=tcpService.getPlaces();
Place[] PlacesToShow=new Place[10];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = new Intent(this, ConnectionService.class);
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
if (isBound) {
PlacesToShow = tcpService.getPlaces();
tcpService.test();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection myConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow = tcpService.getPlaces();
ListAdapter MyAdapter = new MyAdapter(ListActivity.this, PlacesToShow);
ListView ListPlaces = (ListView) findViewById(R.id.MyList);
ListPlaces.setAdapter(MyAdapter);
ListPlaces.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = view.getContext();
TextView textViewItem = ((TextView) view.findViewById(R.id.name));
String name = textViewItem.getText().toString();
TextView textViewItem2 = (TextView) findViewById(R.id.description);
String descripcion = textViewItem2.getText().toString();
Toast.makeText(context, "lugar: " + name + ", descripcion: " + descripcion, Toast.LENGTH_SHORT).show();
}
});
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound=false;
}
};
}