[java]代码库package cn.outofmemory.socket.example;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class App {
public static void main(String[] args) throws IOException {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 19999;
ServerSocket server = new ServerSocket(port);
System.out.println("server waits client");
Socket client = server.accept();
System.out.println("client comes. please write to client");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader consoleRdr = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = consoleRdr.readLine();
if ("quit".equals(line)) {
break;
}
bw.write(line);
bw.write("\r\n");
bw.flush();
} while (true);
bw.close();
server.close();
System.out.println("bye");
}
}
//源代码片段来自云代码http://yuncode.net
package cn.outofmemory.socket.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
final int PORT = 19999;
Socket client = new Socket("localhost", PORT);
BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream()));
do {
String line = rdr.readLine();
System.out.print("server said:");
System.out.println(line);
} while (true);
}
}
//源代码片段来自云代码http://yuncode.net