我有简单的Java服务器:
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
BufferedReader in;
PrintWriter out;
ServerSocket servers = null;
Socket fromClient = null;
// create server socket
try {
servers = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Couldn't listen to port 4444");
System.exit(-1);
}
try {
System.out.print("Waiting for a client...");
fromClient = servers.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
System.exit(-1);
}
in = new BufferedReader(new InputStreamReader(fromClient.getInputStream()));
out = new PrintWriter(fromClient.getOutputStream(), true);
String input;
System.out.println("Wait for messages");
while ((input = in.readLine()) != null) {
if (input.equalsIgnoreCase("exit")) break;
out.println("S ::: " + input);
System.out.println(input);
}
out.close();
in.close();
fromClient.close();
servers.close();
}
}
和简单的Android客户端:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
new MyAsync().execute();
}
---------------------
public class MyAsync extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
try {
fromServer = new Socket("192.168.0.103",4444);
in = new BufferedReader(new InputStreamReader(fromServer.getInputStream()));
out = new PrintWriter(fromServer.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
-------------------
@Override
public void onClick(View v) {
if (v.getId() == R.id.button){
out.println(editText.getText().toString());
}
}
一切顺利。我从Android发送消息到服务器并在服务器中打印此消息。但我想发送Object,例如User:
public class User {
private int age;
private String fio;
public User() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
在Android中我可以写:
User user = new User();
out.print(user);
但我不明白我怎么能在服务器端读到这个?
答案 0 :(得分:0)
您无法使用print()
执行此操作。在发件人处使用ObjectOutputStream.writeObject()
,在接收者处使用ObjectInputStream.readObject()
。您需要将User
课程调整为implement Serializable
并提供private static long serialVersionUID
值。
注意不要写这样的代码。取决于try
块中代码成功的代码应位于同一try
块内。