当前位置: 代码迷 >> Java Web开发 >> 帮忙看下这个java套接字编程:该如何解决
  详细解决方案

帮忙看下这个java套接字编程:该如何解决

热度:127   发布时间:2016-04-17 10:45:03.0
帮忙看下这个java套接字编程:
[code=Java][/code]import java.io.*;
import java.net.*;

public class Client {

  /**
  * @param args the command line arguments
  */
  public static void main(String argv[]) throws Exception {
  String path = new String("C:\\Users\\Lin\\Desktop\\test.tny");
  String buf = null;
  String res = null;
  FileReader fr = new FileReader(path);
  BufferedReader br = new BufferedReader(fr);
  Socket ClientSocket = new Socket("Lin-PC", 6789);
  DataOutputStream outToServer = new DataOutputStream(ClientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(ClientSocket.getInputStream()));
  while ((buf = br.readLine()) != null) {
// System.out.print(buf+"\n");
  outToServer.writeBytes(buf + '\n');
  };
  br.close();
  fr.close();
// res=inFromServer.readLine();
// System.out.print(res);
  outToServer.close();
  }
}

import java.io.*;
import java.net.*;

public class Server {

  /**
  * @param args the command line arguments
  */
  public static void main(String argv[]) throws Exception {
  String path = new String("C:\\Users\\Lin\\Desktop\\res.txt");
  FileWriter fw = new FileWriter(path);
  BufferedWriter bw = new BufferedWriter(fw);
  String sentence = null;
  ServerSocket welcomeSocket = new ServerSocket(6789);
  while (true) { //循环等待
  Socket connectionSocket = welcomeSocket.accept();
  BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
  DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
  while ((sentence = inFromClient.readLine()) != null) {
  bw.write(sentence);
  bw.newLine();
  bw.flush();
// System.out.print(sentence+"\n");
  };
// outToClient.writeBytes("Success!" + "\n");
  fw.close();
  bw.close();
  }
  }
};

注释中的从服务器写字符串入套接字传回客户端无法实现,求原因~

------解决方案--------------------
我就帮你改了这一句
Java code
Socket ClientSocket = new Socket(InetAddress.getLocalHost(), 6789);
------解决方案--------------------
outToClient 写完后 flush一下。。。。
  相关解决方案