码迷,mamicode.com
首页 > 编程语言 > 详细

java web----socket基础

时间:2019-04-20 13:01:04      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:int   客户端连接   span   font   之间   stream   vat   output   out   

服务端和单客户端通信

注意事项:如果服务端或者客户端采用read() 一个字节这种读取数据,只要另一方没有关闭连接,read是永远读取不到-1,会陷入死循环中;

解决方法:加上一个判断,程序员自己跳出循环,比如在while循环中,加上

if(strbuilder.indexOf("\n") > 0){//存在消息结束标志
    break;
}

  

服务端代码

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(8080);
            Socket socket = server.accept();
            System.out.println("客户端连接成功:"+server.getInetAddress().getHostAddress());

            BufferedReader bufRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String s = bufRead.readLine();
            System.out.println("message="+s);


            BufferedWriter bufwrite = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufwrite.write("你好我是服务端\n");
            bufwrite.flush();

            bufwrite.close();
            bufRead.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

客户端代码

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

public class client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",8080);
            BufferedWriter bufWrite = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //如果服务器使用readline来读取数据,那么发送的数据后面必须加上\n;
            bufWrite.write("你好我是客户端\n");
            bufWrite.flush();


            //PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
            //ps.println("dddd");
            //ps.flush();

            BufferedReader bufread = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(bufread.readLine());

            //ps.close();
            bufWrite.close();
            bufread.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

服务器和多客户端通信

 即采用多线程的方式进行处理任务

服务端

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) {
        try {
            ExecutorService es = Executors.newFixedThreadPool(4);
            ServerSocket server = new ServerSocket(8080);
            while (true){
                Socket socket = server.accept();
                System.out.println("有客户端连接");
                es.execute(new ServerHandle(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ServerHandle implements Runnable{
    private Socket socket;
    public ServerHandle(Socket socker){
        this.socket = socker;
    }
    @Override
    public void run() {
        BufferedReader bufRead = null;
        try {
            bufRead = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            char[] chars = new char[1024];
            StringBuilder strbuilder = new StringBuilder();
            int len=-1;
            while ((len=bufRead.read(chars))!=-1){
                strbuilder.append(new String(chars),0,len);
                if(strbuilder.indexOf("\n") > 0){//存在消息结束标志
                    break;
                }
            }
            System.out.println("message="+ strbuilder);
            BufferedWriter bufwrite = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufwrite.write("已经收到你的信息:"+strbuilder+"\n");
            bufwrite.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",8080);
            BufferedWriter bufWrite = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //如果服务器使用readline来读取数据,那么发送的数据后面必须加上\n;
            Scanner input = new Scanner(System.in);
            System.out.println("输入一个发送的信息");
            String x = input.next();
            bufWrite.write(x+"\n");
            bufWrite.flush();

            BufferedReader bufread = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(bufread.readLine());

            bufWrite.close();
            bufread.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

多客户端之间的通信

  

 

java web----socket基础

标签:int   客户端连接   span   font   之间   stream   vat   output   out   

原文地址:https://www.cnblogs.com/yanxiaoge/p/10740302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!