嗨,我是Socket
编程的新手,下面是我尝试使用TCP / IP端口连接并能够成功连接的代码。
连接后,我会向PORT发送一条消息,并且PORT会收到它。
现在,我在从PORT读取数据时遇到问题
样本代码
Thread clientThread = new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket(ipNumber, portNumber);
Log.d("debug","@@socket=="+socket);
// attach to socket's output stream with auto flush turned on
// Send message to the server
out = new PrintWriter(socket.getOutputStream(),true);
Log.d("debug","the message is"+out.toString());
out.println(message);
// Receive data from port and update in Ui
InputStream inputStream = socket.getInputStream();
byte result[] = readBytes(inputStream);
String s = new String(result);
Log.d("debug","the string result is="+s);
} catch (Exception e) {
e.printStackTrace();
final String message = e.getMessage();
Log.d("debug","the error message is"+message);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(!((Activity) MainActivity.this).isFinishing()){
if (message.startsWith("failed to connect")){
new AlertDialog.Builder(MainActivity.this)
.setCancelable(false)
.setTitle(getString(R.string.dialog_alert))
.setMessage(getString(R.string.unable_to_connect_port))
.setPositiveButton(getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
else if (message.equalsIgnoreCase("Connection reset")){
new AlertDialog.Builder(MainActivity.this)
.setCancelable(false)
.setTitle(getString(R.string.dialog_alert))
.setMessage(getString(R.string.connection_closed))
.setPositiveButton(getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
});
}
}
});
clientThread.start();
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
请帮助我了解如何从开放的TCP / IP端口读取数据。任何帮助将不胜感激。