这里我放了一些代码,连接建立,但是每当客户端想要将一些数据发送到服务器数据时,如果客户端在到达服务器后立即解除连接数据如何解决该问题,则无法发送。
我想要的: 如果建立连接并且连接不紧密。
public class Server extends AppCompatActivity {
private ServerSocket serverSocket;
Handler UIHandler;
Thread Thread1 = null;
EditText edText;
public static final int SERVERPORT = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
getSupportActionBar().setTitle("Server");
edText = (EditText) findViewById(R.id.editText);
UIHandler = new Handler();
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
}
class Thread1 implements Runnable {
InetAddress addr;
@Override
public void run() {
Socket socket = null;
try {
addr = InetAddress.getByName(getLocalIpAddress());
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
Thread2 commThread = new Thread2(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String getLocalIpAddress() throws Exception {
String resultIpv6 = "";
String resultIpv4 = "";
for (Enumeration en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements(); ) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
if (inetAddress instanceof Inet4Address) {
resultIpv4 = inetAddress.getHostAddress().toString();
} else if (inetAddress instanceof Inet6Address) {
resultIpv6 = inetAddress.getHostAddress().toString();
}
}
}
}
return ((resultIpv4.length() > 0) ? resultIpv4 : resultIpv6);
}
private class Thread2 implements Runnable {
Socket clientSocket;
BufferedReader input;
String read;
public Thread2(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
read = this.input.readLine();
if (read != null) {
Server.this.runOnUiThread(new Runnable() {
@Override
public void run() {
edText.setText(edText.getText().toString() + "Client says: " + read + "\n");
Log.i("hhFULL", edText.getText().toString());
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:5)
这可能是因为您正在使用的客户端最终发送的消息没有\ n或\ r \ n。下面从inputStream读取一行的代码无限地等待换行符: -
read = this.input.readLine();
答案 1 :(得分:0)
当客户端发送一些数据时,问题就解决了,它需要(ASCII码)换行。