1.创建Client端
创建一个Socket实例指定远程主机IP和端口建立一个TCP连接。
通过Socket套接字的输入输出流(I/O Stream) 进行通信。
public class TCPClient {
public static void main(String args[]){
Writer out =null;
Socket socket = null;
try{
socket = new Socket("127.0.0.1", 10002);
out = new OutputStreamWriter(socket.getOutputStream());
out.write("Hello Server.");
out.flush();
} catch(Exception e){
e.printStackTrace();
}finally{
try{
out.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
2.服务端
服务端创建一个ServerSocket对象,指定端口号,ServerSocket对象等待客户端的连接请求
public class TCPServer {
public static void main(String[] agrs) {
ServerSocket s = null;
Socket socket = null;
Reader in = null;
Writer out = null;
try{
s = new ServerSocket(10002);
socket = s.accept();
in = new InputStreamReader(socket.getInputStream());
char chars[] = new char[64];
int len;
StringBuilder sb = new StringBuilder();
while ((len =in.read(chars))!= -1) {
sb.append(new String(chars, 0, len));
}
System.out.println("from client: " + sb);
out = new OutputStreamWriter(socket.getOutputStream());
out.write("Hello Client.");
out.flush();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
out.close();
in.close();
socket.close();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}