基于Java的2路聊天应用程序无法正常工作

时间:2016-07-11 17:31:45

标签: java network-programming

  

对于其合作伙伴应用,我切换了客户端和服务器代码以及端口。将这两个代码放在两个独立的终端中。他们能够相互联系,但我无法从一个终端向另一个终端发送消息。

import java.net.*;
import java.io.*;
import java.util.Scanner;
class ChatHead1
{  
 public static void main()throws Exception
 {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   //Client   
   Socket sock = new Socket("127.0.0.1", 2000);  
   OutputStream ostream = sock.getOutputStream();  
   DataOutputStream dos = new DataOutputStream(ostream);  
   System.out.print("\nYou:");   
   String message1 = br.readLine();  //Inputting Message For Sending
   dos.writeBytes(message1);

   //Server
   ServerSocket sersock = new ServerSocket(5000);
   System.out.print("\nThem: ");
   Socket sockServ = sersock.accept();
   InputStream istream = sockServ.getInputStream();
   DataInputStream dstream = new DataInputStream(istream);
   String message2 = dstream.readLine();
   System.out.println(message2);    //Printing Received Message

   //Client Close
   dos.close();
   ostream.close();
   sock.close();

   //Server Close
   dstream .close();
   istream.close();
   sockServ.close();
   sersock.close();
 }
}

1 个答案:

答案 0 :(得分:0)

我建议您只使用一个服务器/客户端,因为它是双向连接 我真的不明白为什么你使用客户端服务器。

dos.flush();

之后尝试dos.writeBytes(message1);