要写两个程序:一个客户端的,一个服务端的,写好后,先运行服务端,再运行客户端。
服务端:public class Server{
public static void main(String[] args)throws IOException{
ServerSocket ss = new ServerSocket(30000);
while(true){
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("我是服务器");
ps.close();
s.close();
}
}
}
客服端:
public class Client{
public static void main(String[] args)throws IOException{
Socket socket = new Socket("127.0.0.1",3000);
BufferedReader br = new BufferedReader(new InputStreamReader (socket.getInputStream()));
String line = br.readLine();
System.out.println("来自服务器的数据:"+line);
br.close();
socket.close();
}
}
打德我很辛苦的,只需要将写死的数据用输入流代替就可以聊天了