我正在尝试用Java建立双向通信。为此,我创建了一个简单的客户端 - 服务器程序(我甚至不确定这是否是正确的方法,因为它们都被视为客户端!)。我的要求是,一旦连接了两个程序,它们应该保持连接,并且能够偶尔发送消息。但是,目前我的套接字在发送数据后终止(客户端的Console.WriteLine(nonrpeatedChar);
方法已被执行)。
如何保持连接,以使其持久?
P.S:有没有办法让它以异步方式工作,可能更适合我的要求(我不希望服务器总是在main
内循环)?
客户端:
while
服务器:
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient2 {
String serverHostname = new String("127.0.0.1");
BufferedReader stdIn;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
public void open(){
System.out.println("Attemping to connect to host " + serverHostname
+ " on port 9999.");
try {
echoSocket = new Socket(serverHostname, 9999);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ serverHostname);
}
}
public void send(String s){
out.println(s);
}
public String receive(){
String result = "";
try {
result = in.readLine();
System.out.println("client received: "+result);
if(result==null)
return "0";
} catch (IOException e) {
}
return result;
}
public static void main(String[] args) {
EchoClient2 ec = new EchoClient2();
ec.open();
ec.send("1");
ec.receive();
}
}
答案 0 :(得分:0)
首先抱歉迟到的回答。我也陷入了这个java套接字编程。我还想打开一个套接字并保持打开状态,以便在客户端和服务器之间进行通信。在搜索和阅读了许多书籍和文章后,我找到了最简单的解决方案。您可以在
中使用android life cylcles进行工作在onStart方法
上打开套接字 protected void onStart() {
super.onStart();
new Thread(new Runnable() {
@Override
public void run() {
try {
client = new Socket(ip,Integer.valueOf(port) );
client.setKeepAlive(true);
dataInputStream = new DataInputStream(client.getInputStream());
// readdata=readdata+" "+dataInputStream.readUTF();
readdata=dataInputStream.readUTF();
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
并关闭onStop方法上的套接字
protected void onStop() {
super.onStop();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}