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

Java TCP实现简单的即时通讯

时间:2021-05-24 08:23:25      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:exception   客户端   puts   ace   tac   stream   rgs   bytes   string   

服务端

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+"\n"+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();
                }
            }
        }

    }

检测用户输入的内容(Sencaner)

 

 

Java TCP实现简单的即时通讯

标签:exception   客户端   puts   ace   tac   stream   rgs   bytes   string   

原文地址:https://www.cnblogs.com/chuxinmo/p/14766173.html

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