我是套接字编程的新手,基本上想通过套接字编程将多个数据从服务器(带python的PC)发送到我的Android应用程序。问题是:
1)服务器确认abt 10+连接并停止接收客户端请求。
2)客户端服务器挂起并且不打印单个数据。
尝试同步AsyncTask,但似乎半光谱不能解决它应该是什么。
任何建议让它发挥作用将不胜感激。
package com.example.clientserver;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Semaphore;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
textResponse = (TextView) findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
textResponse.setText("");
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
/*
* MyClientTask myClientTask = new MyClientTask(
* editTextAddress.getText().toString(),
* Integer.parseInt(editTextPort.getText().toString()));
* myClientTask.execute();
*/
RealTimeTask realTimeTask = new RealTimeTask(editTextAddress
.getText().toString(), Integer.parseInt(editTextPort
.getText().toString()));
realTimeTask.start();
}
};
public class RealTimeTask {
String dstAddress;
int dstPort;
String response = "";
RealTimeTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
public void start() {
int loop = 0;
Semaphore semaphore = new Semaphore(1);
while (true) {
try {
Thread.sleep((long) 0.1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
semaphore.acquire();
} catch (InterruptedException e) {
System.out.println("got interrupted!");
}
MyClientTask myClientTask = new MyClientTask(dstAddress,
dstPort);
myClientTask.execute();
semaphore.release();
loop++;
}
}
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
@Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
PYTHON SERVER
import socket
import os
import time
loop = 0
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
s = socket.socket()
host = socket.gethostname()
print get_lan_ip()
port = 5001
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
if loop == 1:
c.send('C')
loop = 0
else:
c.send('D')
loop = 1
c.close()