03
2021
01

socket编程--客户端和服务端聊天室

client
:
package com.xiao.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class Client {
    public static void main(String[] args) {
  //流先开后关
        Socket socket =null;
        OutputStream os =null;
        try {
            //1.要知道服务端的地址,端口号
            InetAddress   serverIP = InetAddress.getByName("127.0.0.1");
            int port=9999;//刚刚我们在服务端定义的端口
            //2.创建一个socket连接
          socket = new Socket(serverIP, port);
            //3.发送消息IO流
            os = socket.getOutputStream();
           os.write("小小不是傻子".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
server:
package com.xiao.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class Server {
    public static void main(String[] args) {
        //流先开后关
        Socket socket=null;
        InputStream in =null;
        ByteArrayOutputStream byteArrayOutputStream =null;
        try {
            //1.我得有一个地址
            ServerSocket serverSocket = new ServerSocket(9999);
            while(true){
                //2.等待客户端连接过来
                socket=serverSocket.accept();
                //3.读取客户端的消息
                in = socket.getInputStream();
                //管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer=new byte[1024];
                int lenth;
                while((lenth=in.read(buffer))!=-1){
                    byteArrayOutputStream.write(buffer,0,lenth);
                }
                System.out.println(byteArrayOutputStream.toString());

            }
             } catch (IOException e) {
            e.printStackTrace();
        }finally {
        if(byteArrayOutputStream!=null){
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }
    }
}


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。