服务器端:
package net;
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String []args) throws Exception{
ServerSocket ss = new ServerSocket(6666);
int count = 0;
while (true){
Socket s = ss.accept();
count ++;
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("第" + count + "个客户:" + dis.readUTF() + s.getInetAddress() + "port" + s.getPort());
dis.close();
s.close();
}
}
}
客户端:
package net;
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String []args) throws Exception{
Socket s = new Socket("127.0.0.1",6666);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("HELLO SERVER !");
System.out.println("I am a client !");
dos.flush();
dos.close();
s.close();
}
}