[英]Need help in Java Socket Programming[server & client]
我使用Java套接字创建了一个名为server.java
的Java服务器,该服务器从Android上的客户端( client.java
)接收字符串,对其进行修改并将修改后的字符串发送给客户端(在我的情况下为Android应用)。
当我尝试同时运行它们时,android应用程序成功将用户输入的字符串发送到服务器。 当服务器接收到字符串时会出现问题,有时服务器不提供任何输出。 但是,如果客户端关闭(或终止),则服务器终端输出为:
message received from client is: null
request: Message sent to the client : i received message:null
message received from client is: null
request: Message sent to the client : i received message:null
message received from client is: null
request: Message sent to the client : i received message:null
message received from client is: null
request: Message sent to the client : i received message:null
message received from client is: null
request: Message sent to the client : i received message:null
这是在台式计算机上运行的Server.java
的代码:
public class Server {
static Socket socket;
static PrintWriter out;
static BufferedReader in;
static int port = 9999;
public static void main(String[] args) {
String query="blank", returnMessage="Server malfunctioning!";
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port "+port);
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
while(true) {
try {
query=in.readLine();
System.out.println("message received from client is: "+query);
//Processing the query.
returnMessage="i received message:"+query;
//Sending the response back to the client.
out.print(returnMessage);
System.out.println("request: Message sent to the client : " + returnMessage);
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
}
这是ServerConnect.java
,它扩展了AsyncTask
:
public class ServerConnect extends AsyncTask<Object, Object, Void> {
String TAG="Server";
String message="empty response";
String ip="EMPTY QUERY";
WebView wb;
TextToSpeech tts;
String host = "192.168.2.3";
int port = 9999;
PrintWriter out;
BufferedReader in;
Socket socket;
ServerConnect(String inp, WebView wbb, TextToSpeech ts) {
ip=inp;
this.wb=wbb;
tts=ts;
}
@Override
protected Void doInBackground(Object... voids) {
Log.d(TAG, "ip value "+ip);
try {
// InetAddress address = InetAddress.getByName(host);
socket = new Socket(host, port);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try {
//Send the message to the server
out.print(ip);
//out.flush();
Log.d(TAG, "request: Message sent to the server : " + ip);
message = in.readLine();
Log.d(TAG, "doInBackground: message" + message);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "My Brain is not working! Reason is: "+e;
} finally {
in.close();
out.flush();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
Log.d(TAG, "doInBackground: finally block");
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Void result) {
// wb.getSettings().setJavaScriptEnabled(true);
if(message!=null) {
wb.loadDataWithBaseURL(null, message, "text/html", "utf-8", null);
tts.speak(stripHtml(message), TextToSpeech.QUEUE_FLUSH, null, null);
if (!(pullLinks(stripHtml(message)).equals(""))) {
wb.setWebViewClient(new WebViewClient());
wb.setWebChromeClient(new WebChromeClient() {});
wb.loadUrl(pullLinks(message));
//ip.setText("");
super.onPostExecute(result);
}
} else {
wb.loadDataWithBaseURL(null, "Message is null!", "text/html", "utf-8", null);
tts.speak("Message is null!", TextToSpeech.QUEUE_FLUSH, null, null);
}
}
public String stripHtml(String html) {
return Html.fromHtml(html).toString();
}
private String pullLinks(String text) {
String links="";
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
urlStr = urlStr.substring(1, urlStr.length() - 1);
links=urlStr;
}
return links;
}
}
readLine()
在流的末尾(即,当对等方关闭连接时readLine()
返回null。 您没有检测到这种情况:您将null视为数据。 当您获得空值时,您需要终止读取循环。
注意: print()
或readLine()
不能引发UnknownHostException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.