作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
客户端:
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TcpClient {
public static void main(String[] args) throws IOException {
try {
byte a[] = { 127,0,0,1 };
InetAddress address = InetAddress.getByAddress(a);
Socket socket = new Socket(address,9876);
OutputStream os = socket.getOutputStream();
PrintWriter out = new PrintWriter(os,true);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String line;
line = "A line sent by the client";
out.println(line);
line = in.readLine();
System.out.println("client got: " + line);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
服务器端:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
public class TcpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9876);
Socket socket = serverSocket.accept();
/*和Client一样了*/
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintWriter out = new PrintWriter(os,true);
String line;
while((line = in.readLine()) != null) {
System.out.println("server got: " + line);
line = "A line sent by the server";
out.println(line);
}
out.close();
in.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
}
}