我正在尝试构建一个应用程序,我可以在两个Android设备之间进行Echo。 我希望他们充当客户端和服务器。
我有以下客户端代码:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private EditText portNumber;
private EditText hostName;
private EditText inputMsg;
private EditText resultMsg;
private InetAddress ia;
private Socket mySocket;
private InputStream isIn;
private OutputStream psOut;
private byte abIn[];
private String sHostName;
private int iPortNumber;
private Handler mHandler;
private int iNumRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hostName = (EditText) findViewById(R.id.editText1);
portNumber = (EditText) findViewById(R.id.editText2);
resultMsg = (EditText) findViewById(R.id.editText3);
inputMsg = (EditText) findViewById(R.id.editText4);
mHandler= new Handler();
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(sHostName);
try {
mySocket = new Socket(serverAddr, iPortNumber);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
}
}
}
class ResponseThread implements Runnable {
@Override
public void run() {
try {
isIn = mySocket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
iNumRead = 0;
abIn = new byte[1024];
try {
iNumRead = isIn.read(abIn);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.post(new Runnable(){
public void run(){
String sResponse, sTemp;
sTemp = new String(abIn, 0, iNumRead);
sResponse = "We got back: " + sTemp;
resultMsg.setText(sResponse);
}
});
}
}
public void myEchoHandler(View view) {
switch (view.getId()) {
case R.id.button1: /* This is the connect button */
sHostName = hostName.getText().toString();
iPortNumber = Integer.parseInt(portNumber.getText().toString());
new Thread(new ClientThread()).start();
break;
case R.id.button2: /* This is the send data button */
byte[] sInputMsg = inputMsg.getText().toString().getBytes();
try {
psOut = mySocket.getOutputStream();
psOut.write(sInputMsg,0, sInputMsg.length);
new Thread(new ResponseThread()).start();
}
catch (Exception ex) {
Toast.makeText(this,"Send data failed. Exception" + ex + "\n", Toast.LENGTH_LONG).show();
}
break;
case R.id.button3: // This is the quit button.
String sTemp2;
try {
mySocket.close();
inputMsg.setText("");
sTemp2 = new String ("Goodbye ...");
resultMsg.setText(sTemp2);
}
catch (Exception ex)
{
Toast.makeText(this,"Close socket failed. Exception " + ex + "\n", Toast.LENGTH_LONG).show();
}
} //end of switch
}//end of myEchoHandler
@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;
}
}
以下服务器端代码:
public class TCPEchoServer {
// define a constant used as size of buffer
static final int BUFSIZE=1024;
// main starts things rolling
static public void main(String args[]) {
if (args.length != 1) {
throw new IllegalArgumentException("Must specify a port!");
}
int port = Integer.parseInt(args[0]);
try {
// Create Server Socket (passive socket)
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket s = ss.accept();
handleClient(s);
}
} catch (IOException e) {
System.out.println("Fatal I/O Error !");
System.exit(0);
}
}
static void handleClient(Socket s) throws IOException {
byte[] buff = new byte[BUFSIZE];
int bytesread = 0;
// print out client's address
System.out.println("Connection from " +
s.getInetAddress().getHostAddress());
// Set up streams
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// read/write loop
while ((bytesread = in.read(buff)) != -1) {
out.write(buff,0,bytesread);
}
System.out.println("Client has left\n");
s.close();
}
}
有关如何进行的任何建议?我正在考虑使用两个类创建应用程序,一个用于客户端代码,另一个用于服务器端代码。
答案 0 :(得分:0)
你总是可以创建两个在不同线程上运行的类,但我会反对这一点,因为我认为你没有找到那些复杂的东西。
这两款Android设备之间的通讯目的是什么? 您可以简单地将其中一个定义为服务器,将另一个定义为客户端,他们可以像这样轻松地进行通信。