1. 程式人生 > >TCP編程

TCP編程

sta servers lose ring quest stat accep tcp throw

Server.java

package com.zby;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static boolean running = true;

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket 
= new ServerSocket(8888); System.out.println("LocalSocketAddress:" + serverSocket.getLocalSocketAddress()); System.out.println("----------------------------------------------------------"); while (running) { Socket socket = serverSocket.accept(); System.out.println(
"connected!"); System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress()); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); String request = dataInputStream.readUTF(); System.out.println("request:" + request); String response
= "Hello,Client!"; DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF(response); System.out.println("response:" + response); System.out.println("disConnected!"); System.out.println(); socket.close(); } serverSocket.close(); } }

Client.java

package com.zby;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888, InetAddress.getLocalHost(), 7777);
        System.out.println("connected!");
        System.out.println("LocalSocketAddress:" + socket.getLocalSocketAddress());
        System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress());
        System.out.println();

        String request = "Hello,Server!";
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        dataOutputStream.writeUTF(request);
        System.out.println("request:" + request);

        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        String response = dataInputStream.readUTF();
        System.out.println("response:" + response);
        System.out.println("disConnected!");
        socket.close();
    }

}

TCP編程