【聊天室2】实现C/S架构聊天实现

一、实现客户端和服务器端的聊天

我们先来看一下socket的源码

我们在代码定义的socket如下

 socket=new Socket(serverIP,port);

源码为

 public Socket(InetAddress address, int port) throws IOException {
        this(address != null ? new InetSocketAddress(address, port) : null,
             (SocketAddress) null, true);
    }
private InetSocketAddressHolder(String hostname, InetAddress addr, int port) {
            this.hostname = hostname;
            this.addr = addr;
            this.port = port;
        }

客户端向服务器端发送hello world

我们都知道Tcp/ip协议组的四元组就是(源ip 源端口,目的ip 目的端口)

在我们这里只用到了源ip和源端口

客户端代码

package com.lei;

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

public class ClientDemo01 {
    public static void main(String[] args) throws IOException {
       // InetAddress serverIP=InetAddress.getByName("127.0.0.1");
        InetAddress serverIP=null;
        int port;
        Socket socket=null;
        OutputStream os=null;
        try {
            //本机ip
            serverIP=InetAddress.getByName("127.0.0.1");
            //设置交互端口号
            port=9999;
            //设置套接字
            socket=new Socket(serverIP,port);
            //输出流
            os=socket.getOutputStream();
            //写下hello world
            os.write("hello world".getBytes());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            //关闭资源 从下到上
            os.close();
            socket.close();


        }
    }
}

服务端代码

package com.lei;

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

public class ServeDemo02 {


    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        int port=9999;
        try {
            //该类实现了将数据写入字节数组的输出流
            baos=new ByteArrayOutputStream();
            //类实现了服务器套接字。 服务器套接字等待通过网络进入的请求。 它根据该请求执行一些操作,然后可能将结果返回给请求者
            serverSocket=new ServerSocket(9999);
            //侦听要连接到此套接字并接受它。   侦听到了我们在服务端定义的socket
            socket=serverSocket.accept();
            //输出流
            is=socket.getInputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            //关闭资源 从下到上
            baos.close();
            is.close();
            socket.close();
            serverSocket.close();
        }
    }
}

要注意在运行的时候一定运行服务器端代码 然后马上运行客户端代码

否则会出现连接失败的情况。

原文地址:https://www.cnblogs.com/cckong/p/14130293.html