socket通讯简单例子

【服 务 器 端】:

import java.io.*;
import java.net.*;

public class MyServer {
public static void main(String[] args) throws IOException {
   ServerSocket server = new ServerSocket(5678);
   Socket client = server.accept();
   BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
   PrintWriter out = new PrintWriter(client.getOutputStream());
   while (true) {
    String str = in.readLine();
    System.out.println(str);
    out.println("has receive....");
    out.flush();
    if (str.equals("end"))
     break;
   }
   client.close();
}
}

【客 户 端】:

import java.net.*;
import java.io.*;

public class Client {
static Socket server;

public static void main(String[] args) throws Exception {
   server = new Socket(InetAddress.getLocalHost(), 5678);
   BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
   PrintWriter out = new PrintWriter(server.getOutputStream());
   BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));

   while (true) {
    String str = wt.readLine();
    out.println(str);
    out.flush();
    if (str.equals("end")) {
     break;
    }
    System.out.println(in.readLine());
   }
   server.close();
}
}

你可能感兴趣的:(exception,socket,server,String,import,通讯)