// tcpServer
// usage : java tcpServer
// default port is
// connection to be closed by client
// this server handles only
import
import java
public class tcpServer {
public static void main(String args[]) {
int port;
ServerSocket server_socket;
BufferedReader input;
try {
port = Integer
}
catch (Exception e) {
System
port =
}
try {
server_socket = new ServerSocket(port);
System
server_socket
// server infinite loop
while(true) {
Socket socket = server_socket
System
socket
input = new BufferedReader(new InputStreamReader(socket
// print received data
try {
while(true) {
String message = input
if (message==null) break;
System
}
}
catch (IOException e) {
System
}
// connection closed by client
try {
socket
System
}
catch (IOException e) {
System
}
}
}
catch (IOException e) {
System
}
}
}
// tcpClient
// usage : java tcpClient
// default port is
import
import java
public class tcpClient {
public static void main(String[] args) {
int port =
String server =
Socket socket = null;
String lineToBeSent;
BufferedReader input;
PrintWriter output;
int ERROR =
// read arguments
if(args
server = args[
try {
port = Integer
}
catch (Exception e) {
System
port =
}
}
// connect to server
try {
socket = new Socket(server
System
socket
}
catch (UnknownHostException e) {
System
System
}
catch (IOException e) {
System
System
}
try {
input = new BufferedReader(new InputStreamReader(System
output = new PrintWriter(socket
// get user input and transmit it to server
while(true) {
lineToBeSent = input
// stop if input line is
if(lineToBeSent
output
}
}
catch (IOException e) {
System
}
try {
socket
}
catch (IOException e) {
System
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26703.html