簡単なTCP/IPサービス側クライアント対話

4740 ワード

//TCP/IP 



import java.io.ObjectOutputStream;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;



public class TestSocketServer {



    ServerSocket serverSocket;

    int portNumber=9001;

    Socket socket;

    String str;

    

    public TestSocketServer(){

        str="Hello,I am Server!";

        

        try {

            // serverSocket 

            serverSocket=new ServerSocket(portNumber);

            // xx 

            socket=serverSocket.accept();

            // 

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

            

            oos.writeObject(str);

            // 

            oos.close();

            socket.close();

        } catch (Exception e) {



            e.printStackTrace();

        }

        

    }

    

    public static  void main(String[]args){

        TestSocketServer tss=new TestSocketServer();

    }

}
//TCP/IP 



import java.io.ObjectInputStream;

import java.net.InetAddress;

import java.net.Socket;



public class TestSocketClient {



    Socket socket ;

    int portNumber=9001;

    String string="";

    

    public TestSocketClient(){

        try {

            // Socket , IP 

            socket =new Socket(InetAddress.getLocalHost(),portNumber);

            // , 

            ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());

            // 

            string=(String)ois.readObject();

            System.out.println(string);

            

        } catch (Exception e) {

            e.printStackTrace();

        }

        

    }

    public static void main(String[]args){

        

        TestSocketClient tcp=new TestSocketClient();

    }

}