服务器端:
import java.io.*;
import java.net.*;
public class TestTcpServer {
public static void main(String[] args) {
try{
ServerSocket serS = new ServerSocket(6666);
while(true){
Socket so = serS.accept();
System.out.println("A client has connected!");
DataInputStream dis = new DataInputStream(so.getInputStream());
System.out.println("What does client say? " + dis.readUTF());
dis.close();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
客户端
import java.net.*;
import java.io.*;
public class TestTcpClient {
public static void main(String[] args) {
try{
Socket so = new Socket("127.0.0.1",6666);
OutputStream os = so.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello Server!");
dos.flush();
dos.close();
so.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}