【发布时间】:2016-11-02 18:53:53
【问题描述】:
我遇到了一些关于 Java 套接字和 golang 的问题。我正在尝试开发一个向 android 客户端发送/接收字节数组的 golang 服务器。现在 android 客户端可以将字节数组发送到 go 服务器,但无法从 go 服务器接收任何内容。我附上了下面的代码。
到达 in.read(); 时代码卡住了;我尝试in.available() 查看输入流中有多少字节。它总是显示 0:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button regButton = (Button) findViewById(R.id.regbut);
msg = (TextView) findViewById(R.id.msg);
regButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
new Thread(new Runnable() {
@Override
public void run() {
byte[] array;
BigInteger mykey = mykey(publicKey);
System.out.println(mykey);
BigInteger rawkey = generater.modPow(mykey,publicKey);
BigInteger serverRawKey;
System.out.println(rawkey);
array = rawkey.toByteArray();
System.out.println(rawkey.bitCount());
try{
Socket con = new Socket("149.166.134.55",9999);
OutputStream out = con.getOutputStream();
InputStream in = con.getInputStream();
DataOutputStream dOut = new DataOutputStream(out);
//DataInputStream din = new DataInputStream(in);
byte[] data = new byte[10];
dOut.write(array);
TimeUnit.SECONDS.sleep(10);
System.out.println(in.available());
in.read(data);
con.close();
}catch (Exception e){
System.out.println(e);
}
}
}).start();
}
});
}
这里是 go 代码。如果我删除 in.read();在java中一切正常。但是当我添加 in.read(); 时它会暂停;
var publickey *big.Int
func ClientListen(port string) {
ln, err := net.Listen("tcp", port)
if err != nil {
fmt.Println("error\n")
fmt.Println(err)
return
}
for {
nc, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go recivemsg(nc)
}
}
func recivemsg(nc net.Conn) {
publickey = big.NewInt(15485863)
var msg []byte
var buf bytes.Buffer
rawkey := big.NewInt(0)
io.Copy(&buf, nc)
fmt.Println("total size:", buf.Len())
msg = buf.Bytes()
rawkey = rawkey.SetBytes(msg)
fmt.Println(msg, " ", rawkey)
r := rand.New(rand.NewSource(99))
myraw := big.NewInt(0)
myraw = myraw.Rand(r, publickey)
fmt.Println(myraw)
newmsg := myraw.Bytes()
nc.Write(newmsg)
nc.Close()
fmt.Println(nc.RemoteAddr())
}
func main() {
ClientListen(":9999")
}
感谢大家花时间阅读我的问题
【问题讨论】:
-
您的 Go 代码依靠连接关闭来发出消息结束的信号。发件人要么需要关闭连接,要么您需要一些其他协议来分隔消息。
-
所以我需要建立另一个连接以将消息发送回 Java?
-
不,您只需要一个发送消息的协议:固定长度、长度前缀、换行符分隔、http 等。TCP 连接是一个流,它不会发送单独的消息。