Java Android TCP 服务器客户端通信
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20263522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android TCP Server Client Communication
提问by user934820
I found a well written tutorial herefor server client communication on android. Works like a charm. But it is only one way communication. I am trying to listen server response in client but not know where I am wrong here. Here is the code for server where I am trying to make changes.
我在这里找到了一篇写得很好的教程,用于在 android 上进行服务器客户端通信。奇迹般有效。但这只是一种沟通方式。我正在尝试在客户端侦听服务器响应,但不知道我错在哪里。这是我尝试进行更改的服务器代码。
Server
服务器
public class Server extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 8080;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
@Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
if (read == null ){
Thread.currentThread().interrupt();
}else{
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.write("TstMsg");
updateConversationHandler.post(new updateUIThread(read));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
@Override
public void run() {
text.setText("Client Says: "+ msg + new Date() + "\n");
}
}
}
Client
客户
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8080;
private static final String SERVER_IP = "192.168.104.107";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read = in.readLine();
System.out.println("MSG:" + read);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Update
更新
When client send any message to server the message is received by server but when server send its response
当客户端向服务器发送任何消息时,服务器会收到消息,但是当服务器发送响应时
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.write("TstMsg");
and in client
并在客户端
String read = in.readLine();
System.out.println("MSG:" + read);
It dose not recieved by client or we can say server listen clients message but client not. I have added both permissions in manifest.
它不会被客户端收到,或者我们可以说服务器监听客户端消息但客户端没有。我在清单中添加了这两个权限。
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
Update After a long hang comes these errors.
更新 长时间挂起后出现这些错误。
11-28 18:35:45.786: E/GTalkService(292): connectionClosed: no XMPPConnection - That's strange!
11-28 18:35:48.806: D/ConnectivityService(148): handleInetConditionHoldEnd: net=1, condition=0, published condition=0
11-28 18:35:54.526: I/GTalkService/c(292): [AndroidEndpoint@1090563472] connect: acct=1000000, state=CONNECTING
11-28 18:35:55.176: D/dalvikvm(1167): GC_CONCURRENT freed 495K, 9% free 6604K/7239K, paused 2ms+3ms
11-28 18:35:55.226: D/Finsky(1167): [1] 5.onFinished: Installation state replication succeeded.
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): Problem with socket or streams.
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): java.net.ConnectException: failed to connect to www.google-analytics.com/173.194.39.41 (port 80): connect failed: ETIMEDOUT (Connection timed out)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at libcore.io.IoBridge.connect(IoBridge.java:114)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at java.net.Socket.connect(Socket.java:842)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at com.google.android.apps.analytics.t.run(Unknown Source)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at android.os.Handler.handleCallback(Handler.java:605)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at android.os.Handler.dispatchMessage(Handler.java:92)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at android.os.Looper.loop(Looper.java:137)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at android.os.HandlerThread.run(HandlerThread.java:60)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at libcore.io.Posix.connect(Native Method)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-28 18:37:18.276: W/GoogleAnalyticsTracker(349): ... 9 more
11-28 18:37:29.016: D/dalvikvm(349): GC_CONCURRENT freed 1258K, 35% free 8238K/12487K, paused 2ms+8ms
回答by Peter
I am still not to sure about what you are trying to achieve. Your error -log shows a XMPPConnection - Error. XMPP isn't handled over the port you are using in the posted code, so this error message could be either from a different part of your application. The other error message is related to an HTTP - Connection for Google analytics and neither is related to the code snippet that you posted. You should downtrace your problem by: catching possible exceptions, Log.d with a tag you can filter your error - messages by. The hint from Martin James is good I think, so trying to switch to a byte - wise reading of your inputstream at least for verification and downtracing if you receive any data from your server - connection is also a good idea.
我仍然不确定您要实现的目标。您的错误日志显示 XMPPConnection - 错误。XMPP 不会通过您在发布的代码中使用的端口进行处理,因此此错误消息可能来自应用程序的不同部分。另一条错误消息与 HTTP - Connection for Google 分析相关,与您发布的代码段无关。您应该通过以下方式跟踪您的问题:捕获可能的异常,Log.d 带有您可以过滤错误消息的标签。我认为 Martin James 的提示很好,因此尝试切换到以字节方式读取输入流,至少用于验证和向下跟踪(如果您从服务器接收到任何数据)- 连接也是一个好主意。
回答by Martin James
readLine() expects an actual line :' A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.'
readLine() 需要一个实际的行:' 一行被认为是由换行符 ('\n')、回车符 ('\r') 或回车符中的任何一个终止,后面紧跟换行符。 '
You should therefore send one, eg. with BufferedWriter.newLine().
因此,您应该发送一个,例如。使用 BufferedWriter.newLine()。
回答by kumar
Have you written the following snippet in your code
您是否在代码中编写了以下代码段
out.flush();
after
后
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.write("TstMsg");
回答by Les
Have you tried adding a new line ("\n"
) when trying to write? Try out.write("TstMsg"+ "\n")
instead.
您是否尝试"\n"
在尝试写入时添加新行 ( )?试试吧out.write("TstMsg"+ "\n")
。
回答by Syed Maruf Ahmed
If you are trying to connect to a web server. As far as I know web server handles http protocol and you are trying to connect to a webserver simply with tcp/ip using socket. You will not get expected response as you are violating protocol standard. your option would be if you want to connect to a web server either you use android HttpURLConnection related classes or you create your own application server using severSocket related classes in any programming language to handle your clients.
如果您尝试连接到 Web 服务器。据我所知,Web 服务器处理 http 协议,而您正尝试使用套接字通过 tcp/ip 简单地连接到 Web 服务器。由于您违反了协议标准,您将不会得到预期的响应。您的选择是,如果您想连接到 Web 服务器,要么使用 android HttpURLConnection 相关类,要么使用任何编程语言中的 severSocket 相关类创建自己的应用程序服务器来处理您的客户端。
回答by Travis Foster
final Socket s = new Socket();
s.connect(new InetSocketAddress(mHost, mPort), 20000);
final DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.write(("This is a message." + "\r\n").getBytes());
dos.flush();
Alternatively:
或者:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String outgoingMsg = "This is a message." + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();