word
java和C#之间SOCKET通信的问题 一、服务器端(使用java编写) /**
* 监听客户端的请求 * */
private static void socketService() {
ExecutorService exec = Executors.newCachedThreadPool(); try {
ServerSocket server=new ServerSocket(5678); int i = 1; while(true) {
MyLogManager.InfoLog(log, null,\等待连接第\个用户...\ try {
Socket client=server.accept();
MyLogManager.InfoLog(log, null,\第\个用户连接完成!\
word
exec.execute(new PDAServerWithDB(client)); }
catch(Exception whileExp) {
String msg = \多线程处理连接失败!\ MyLogManager.ErrorLog(log, whileExp, msg); } i++; } }
catch(IOException ioe) {
String msg = \连接失败!\
MyLogManager.ErrorLog(log, ioe, msg); exec.shutdown(); } }
具体对于Socket信息的接受和发送在PDAServerWithDB类中处理 信息处理分为:接收数据和发送数据
服务端接收数据一律采用ReadLine()方法,这就要求客户端在发送请求时要有行结束符。 服务器的接收发送数据的代码
word
a)。构造输入输出流
InputStream inPut = s.getInputStream(); OutputStream outPut = s.getOutputStream(); PrintWriter outWriter=new PrintWriter(outPut); BufferedReader inputReader =new BufferedReader(new InputStreamReader(inPut)); b。接收客户端请求的代码
String request = inputReader.readLine(); request = request.trim();
request = request.replaceAll(\c。向客户端发送文本数据的代码 outWriter.println(strInfo); outWriter.flush(); d)。向客户端发送文件的代码 // 发送文件长度
File file = new File(filePath); byte[] outBytes = new byte[1024]; int count = 0;
FileInputStream fileInput = new FileInputStream(file); ByteArrayOutputStream ow = new ByteArrayOutputStream(); while ((count = fileInput.read(outBytes)) > 0) { MyLogManager.DebugLog(log, null, String.valueOf(count));