1

我是 Java 编程新手,我编写了一个简单的服务器(VB.NET)/客户端(Java)程序。来自 Java 的文本已成功发送到 VB.Net,但在 Java 中未收到来自 VB.Net 的响应

我错过了什么吗?

这是我的代码

VB.NET(服务器)

Imports System.Net.Sockets, System.Text
Public Class Form1

Dim server As New TcpListener(9999)
Dim client As New TcpClient
Dim stream As NetworkStream

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Me.Text = "Waiting...."
    server.Start()
    client = server.AcceptTcpClient
    'Receive msg'
    stream = client.GetStream()
    Dim r_byt(client.ReceiveBufferSize) As Byte
    stream.Read(r_byt, 0, client.ReceiveBufferSize)
    Dim str As String = Encoding.ASCII.GetString(r_byt)
    Label1.Text = str
    'Send msg'
    Dim s_byt() As Byte = Encoding.UTF8.GetBytes("got it")
    stream.Write(s_byt, 0, s_byt.Length)
    stream.Close()
End Sub

End Class

Java(客户端)

import java.io.*;
import java.net.*;

public class frmClient {

public static void main(String[] args) throws Exception{
    frmClient myCli = new frmClient();
    myCli.run();

}

public void run() throws Exception{
    Socket socket = new Socket("192.168.0.100", 9999);
    PrintStream stream = new PrintStream(socket.getOutputStream());
    stream.println("Hello Server...");

    BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String string = buffer.readLine();
    System.out.println(string);
}
}
4

2 回答 2

1

好吧,我不确定这里有什么问题,但我建议将字符串拆分为字符,然后将数组的长度写入输出流。然后,Java 中的 for 循环可以从 DataInputStream 中单独读取字符,然后将其组装成字符串

DataInputStream dis = new DataInputStream(socket.getInputStream());
String chars = "";
for (int i = 0; i < dis.readInt(); i ++) {
    chars += dis.readChar();
}
System.out.println(chars);

此外,vbs 流不是写行,它只是写字符。尝试在末尾附加一个断线字符“得到它\n”

于 2012-12-29T19:46:30.030 回答
1

你的Java客户看起来不错。您只需要确保发送换行符以匹配BufferedReader.readLine语句。代替:

Dim s_byt() As Byte = Encoding.UTF8.GetBytes("got it")

Dim s_byt() As Byte = Encoding.UTF8.GetBytes("got it" + vbCr)

在您的服务器中。


旁白:我会在这里看看线程服务器,因为它在侦听连接时阻塞了应用程序。这是一个例子

于 2012-12-30T04:03:45.980 回答