我是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);
}
}
答案 0 :(得分: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流也不是写行,只是简单地写字符。尝试在最后添加一个breakline字符“得到它\ n”
答案 1 :(得分: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)
在您的服务器中。
除了:我会在这里查看线程服务器,因为它会在侦听连接时阻止应用程序。这是example