我制作了一个基于 TCP/IP 的基本项目,其中服务器侦听客户端,然后提供传入数据的大写句子。
服务器.java:
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(7948);
Socket s= ss.accept();
System.out.print("Server connected\n");
BufferedInputStream bis = new BufferedInputStream (s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream (s.getOutputStream());
while(true)
{
int a = bis.available();
byte b[] = new byte[a];
bis.read(b);
String str = new String(b);
str = str.toUpperCase();
b = str.getBytes();
bos.write(b,0,b.length);
bos.flush();
if(str.equals("BYE"))
break;
else
continue;
}
System.out.print("\nServer Disconnecting");
String str = "Adios Amigo";
bos.write(str.getBytes());
bos.flush();
bis.close();
bos.close();
ss.close();
s.close();
}
}
客户端.java:
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws Exception
{
BufferedReader clientStream = new BufferedReader(new InputStreamReader(System.in));
String str;
int a;
byte[] b;
Socket s = new Socket(InetAddress.getLocalHost(), 7948);
BufferedOutputStream bos = new BufferedOutputStream (s.getOutputStream());
BufferedInputStream bis = new BufferedInputStream (s.getInputStream());
one:while(true)
{
str = clientStream.readLine();
b =str.getBytes();
bos.write(b);
bos.flush();
a=bis.available();
b = new byte[a];
bis.read(b);
str = new String (b);
str.trim();
System.out.print("The server says: "+str);
if (str.equals("BYE"))
{
bis.read(b);
str = new String (b);
System.out.print("The server says: "+str);
break one;
}
}
s.close();
clientStream.close();
bos.close();
bis.close();
}
}
该程序运行正常,除了一个问题,客户端的输出来自两次输入。这意味着我必须从客户端提供两个输入才能获得第一个输出,并且继续进行。我无法跟踪错误。有人可以帮忙吗?