我正在学习android套接字编程。代码如下。在第一次单击该按钮时,消息将成功发送到服务器,但是在第二次单击消息未进入服务器之后,它也没有显示任何错误。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private InetAddress address;
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) this.findViewById(R.id.Send);
send.setOnClickListener(this);
}
@Override
public void onClick(View v) {
new Sender().execute("xxx.xxx.xx.xxx");
}
private class Sender extends AsyncTask<String, Void, Void> {
private Socket socket;
private Connector connector;
public Sender() {}
@Override
protected Void doInBackground(String... params) {
try {
address = InetAddress.getByName(params[0]);
socket = new Socket(address, 10001);
connector = new Connector(socket);
connector.write("Hello server, this is client");
} catch (UnknownHostException e) {
Log.d("Error", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("Error", e.getLocalizedMessage());
}
return null;
}
}
}
public class Connector {
private Socket socket;
private PrintWriter writer;
public Connector(Socket soc) {
socket = soc;
try {
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
Log.d("Error", e.getLocalizedMessage());
}
}
public void write(String message) {
writer.println(message);
}
}