Java TCP实现简单的即时通讯

public static void main(String[] args) {    ServerSocket serverSocket = null;    Socket socket = null;    InputStream inputStream = null;    ByteArrayOutputStream outputStream = null;    try {        //创建一个连接        serverSocket = new ServerSocket(9999);        while (true){            //等待连接            socket = serverSocket.accept();            //读取信息            inputStream = socket.getInputStream();            outputStream = new ByteArrayOutputStream();            byte[] bytes = new byte[1024];            int len;            if((len=inputStream.read(bytes))!=-1){                outputStream.write(bytes,0,len);            }            System.out.println(outputStream.toString());        }    } catch (IOException e) {        e.printStackTrace();    }finally {        if(outputStream!=null){            try {                outputStream.close();            } catch (IOException e) {                e.printStackTrace();            }        }        if(inputStream!=null){            try {                inputStream.close();            } catch (IOException e) {                e.printStackTrace();            }        }        if(socket!=null){            try {                socket.close();            } catch (IOException e) {                e.printStackTrace();            }        }        if(serverSocket!=null){            try {                serverSocket.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

客户端代码

public static void send(String msg){

Socket socket = null;

OutputStream o = null;

//获取到服务器ip

try {

String name = "他:";

InetAddress ip = InetAddress.getByName("127.0.0.1");

int port = 9999;

socket = new Socket(ip,port);

o = socket.getOutputStream();

o.write((name+" "+msg).getBytes());

} catch (Exception e) {

e.printStackTrace();

}finally {

if(o!=null){

try {

o.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(socket!=null){

try {

socket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章