集册 Java实例教程 从套接字读取

从套接字读取

欢马劈雪     最近更新时间:2020-01-02 10:19:05

506
从套接字读取

import java.io.IOException;// from 时 代 J a v a

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.InetAddress;

import java.net.Socket;

import java.net.UnknownHostException;

 


public class SocketClient{

 

    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{

        //get the localhost IP address, if server is running on some other IP, you need to use that

        InetAddress host = InetAddress.getLocalHost();

        Socket socket = null;

        ObjectOutputStream oos = null;

        ObjectInputStream ois = null;

        for(int i=0; i<5;i++){//from nowjava.com - 时代Java

            //establish socket connection to server

            socket = new Socket(host.getHostName(), 495);

            //write to socket using ObjectOutputStream

            oos = new ObjectOutputStream(socket.getOutputStream());

            System.out.println("Sending request to Socket Server");

            if(i==4)oos.writeObject("exit");

            else oos.writeObject("Ciat ciat");

            //read the server response message

            ois = new 
展开阅读全文