我估计是输入输出流的问题。在eclipse下运行时总不能得到设想的结果。。importjava.net.*;importjava.io.*;publicclassServerTCP{publicstaticvoidmain(String[]args)throwsException...
我估计是输入输出流的问题。在eclipse下运行时总不能得到设想的结果。。import java.net.*;
import java.io.*;
public class ServerTCP {
public static void main(String[] args) throws Exception
{
ServerSocket serversocket=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
serversocket=new ServerSocket(8000);
socket=serversocket.accept();
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
byte[] buf=new byte[100];
in.read(buf);
String str=new String(buf);
System.out.println("On Server..."+" "+str);
str="message form server...";
buf=str.getBytes();
out.write(buf);
}
}
import java.net.*;
import java.io.*;
public class UserTCP {
public static void main(String[] args) throws Exception
{
Socket socket=new Socket("localhost",8000);
DataInputStream in=new DataInputStream(socket.getInputStream());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
String str="I am client";
byte[] buf =new byte[100];
buf=str.getBytes();
out.write(buf);
in.read(buf);
str=new String(buf);
System.out.println("On client..."+" "+str);
}
}
首先,谢谢各位大大们的解答。大大们提到的错误我改正了下,可是仍无法得到我想要的答案。。以下是我修改后运行的结果:
server端: byte[] bufR=new byte[100];
byte[] bufW=new byte[100];
in.read(bufR);
String str=new String(bufR);
System.out.println("On Server..."+" "+str);
str="message form server...";
bufW=str.getBytes();
out.write(bufW);
user端:
String str="I am client";
byte[] bufW =new byte[100];
bufW=str.getBytes();
out.write(bufW);
byte[] bufR=new byte[100];
in.read(bufR);
str=new String(bufR);
System.out.println("On client..."+" "+str);
On Server... I am client□□□□□□□□□□□□□□□□□□□□□□□□□□□□
问题是,server端的write方法没运行起?还是user端没收到数据?
悲剧的是。第二次运行得到
On client... message form server...□□□□□□□□□□□□□□□□□□□□□□□□□□□□
两个只有一个显示出来了!!郁闷啊
展开