手记

java socket 通信socketServer 单线程通信

package com.cqupt;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;

import org.ansj.domain.Result;
import org.ansj.splitWord.analysis.NlpAnalysis;

import DeepNeural.DeepMind;

import com.ansj.vec.Word2VEC;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;

public class singleThred {//  能收能发

    public static void main(String[] args) throws IOException {
        System.out.println("***服务器65431即将启动,等待客服端连接***");
            while(true){
                TestServer();
            }

    }

    public static void  TestServer() throws IOException {
            // 1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听
            ServerSocket serverSocket = new ServerSocket(65432);
            // 2.调用accept()方法开始监听,等待客服端的连接
            //System.out.println("***服务器即将启动,等待客服端连接***");
            Socket socket = serverSocket.accept();
            // 3.获取输入流,并读取客服端信息
            InputStream is = socket.getInputStream();//字节输入流
            InputStreamReader isr = new InputStreamReader(is);//将字节流转换为字符流
            BufferedReader br = new BufferedReader(isr);//为输入流添加缓冲

            String info = null;
            String infoResult = "";
            String sendString="";

            while ((info=br.readLine())!=null) {//循环读取客服端的信息
                if (info.equals("")) {
                    break;
                }
                if (info.equals(" ")) {
                    break;
                }
                infoResult = infoResult+info;

            }
            socket.shutdownInput();//关闭输入流

            // 4.响应客服端  即给客服端发送信息
            OutputStream os = socket.getOutputStream();//字节输出流
            PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流

            //=====================================================

            System.out.println(" In:"+infoResult);
            if (!infoResult.equals("")) {
                sendString =OtherHandel.MyResult(infoResult.trim());
                }   

            // 4.响应客服端  即给客服端发送信息
            os = socket.getOutputStream();//字节输出流
            pw = new PrintWriter(os);//将输出流包装为打印流
            //sendString = Integer.toString(BiaoQian);  

            pw.write(sendString);//  写入客户端的信息+只能是纯数字字符串
            System.out.println("Out:"+sendString+"\r\n");           
            pw.flush();//调用flush()方法将缓冲输出

            // 5.关闭资源
            pw.close();
            os.close();
            br.close();
            isr.close();
            is.close();
            socket.close();
            serverSocket.close();
}
}
0人推荐
随时随地看视频
慕课网APP