Socket之TCP通信

来源:互联网 发布:海康威视算法工程师ai 编辑:程序博客网 时间:2024/05/17 04:14

简要笔记,后看

实现的是多线程的通信

服务器

public class Server {public static void main(String[] args) {try {//创建ServerSocket实例ServerSocket serverSocket=new ServerSocket(3444);Socket socket=null;//监听,直到有客户端的请求,将其赋给Socketwhile(true){socket=serverSocket.accept();//开启一个线程去接待客户端传来的socketnew ServerThread(socket).start();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

服务器线程类

public class ServerThread extends Thread{private Socket socket=null;private static int count=0;public ServerThread(Socket socket) {// TODO Auto-generated constructor stubthis.socket=socket;}@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();//从客户端获取的socket对象的获得输入的信息InputStream in=null;InputStreamReader inr=null;BufferedReader br=null;OutputStream os=null;PrintWriter pw=null;try {in = socket.getInputStream();//字节流转字符流inr=new InputStreamReader(in);    //缓存    br=new BufferedReader(inr);    String string;    while((string=br.readLine())!=null){    System.out.println("客户端——>服务器:"+string);    }    //当在获取输出流之前,一定要关闭输入流,反之亦然,不然会报错,    socket.shutdownInput();        os=socket.getOutputStream();    pw=new PrintWriter(os);    synchronized ("123") {pw.write("Welcome!"+"你是第"+(++count)+"个用户");}    pw.flush();//    Thread.sleep(3000);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {    try {    //关闭socket的输入流//socket.shutdownOutput();//关闭其他流        br.close();        inr.close();        in.close();        pw.close();        os.close();        //关闭socket        socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}    }}}

客户端类

public class Client {public static void main(String[] args) {try {//新建socket类,相当于向服务器发送请求Socket socket=new Socket("localhost", 3444);//获取socket的输出流OutputStream os=socket.getOutputStream();//将字节输出流转化为打印流PrintWriter pw=new PrintWriter(os);//写入pw.write("登入名:adlkl;密码:sdsd4");pw.flush();/* * 对于socket而言,在使用输出流时,要关闭输入流,反之同理 * 对于其他流,最好是写在最后 */socket.shutdownOutput();InputStream is=socket.getInputStream();BufferedReader br=new BufferedReader(new InputStreamReader(is));String string=null;while((string=br.readLine())!=null){System.out.println("服务器——>客户端"+string);}socket.shutdownInput();//关闭操作pw.close();os.close();socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("hjhjhj");}}}



0 0
原创粉丝点击