Java TCP实现简单的即时通讯

时间:2021-05-24 08:23:25   收藏:0   阅读:0

服务端

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)

 

 
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!