Golang服务器将字节数组发送到Android。

huangapple go评论102阅读模式
英文:

golang server sending byte array to Android

问题

我在Java socket和golang方面遇到了一些问题。我正在尝试开发一个golang服务器,将字节数组发送/接收到一个Android客户端。现在Android客户端可以将字节数组发送到golang服务器,但无法从golang服务器接收任何内容。我在下面附上了代码。

当代码执行到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();
        }
    });
}

以下是golang代码。如果我在Java中删除in.read(),一切都正常工作。但是当我添加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")
}

感谢大家抽出时间阅读我的问题。

英文:

I have met some issue with Java socket and golang. I am trying to develop a golang server that sends/receives byte array to an android client. now the android client can send byte array to go server but cannot receive anything from go server. I have attached the code below.

The code got stuck when reach in.read(); I tried in.available() to see how many bytes are in the inputstream. it always shows 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();
}
});
}

here is the go code. if i remove in.read(); in java everything works just fine. but it pauses when I add 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")
}

thanks guys for taking your time to read my question

答案1

得分: 0

io.Copy(&buf, nc)在Go端将继续从连接的输入流中读取,直到它关闭。在Java端,您尝试从连接的输入流中读取,但是Go端仍在等待进一步的输入,因为Java仍然保持其输出流(即Go的输入流)处于打开状态。

解决方案:在Java端,在完成写入后,使用套接字的shutdownOutput()方法关闭输出流。

英文:

io.Copy(&buf, nc) on Go side will continue to read from the connection's input stream until it's closed. On Java side, you try to read from the connection's input stream, but Go side is still waiting for further input, since Java is still keeping its output steam (Go's input stream) open.

Solution: on Java side, close the output stream using the socket's shutdownOutput() method after you are done writing to it.

huangapple
  • 本文由 发表于 2016年11月3日 02:53:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/40387671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定