经过一个多月枯燥的Java编程基础学习,终于学到net了,呵呵.. .. ..挺好玩
上服务器端程序:
TestTCPServer
package socketdemo;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TestTCPServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9999);
while(true){
System.out.println("----------服务端已经启动------------");
Socket s = ss.accept();
// System.out.println(s.getLocalPort()+" "+s.getPort()+" "+s.getLocalAddress().getHostAddress());
// System.out.println(s.getInetAddress().getHostAddress()+":"+s.getPort()+
// "客户端已经 连接上服务器ServerSocket");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("客户端【"+s.getInetAddress().getHostAddress()+"::"+s.getPort()+"】已经连接");
dos.writeUTF("服务器端写入客户端的数据:客户端【"+s.getInetAddress().getHostAddress()+"::"+s.getPort()+
"】已经连接上服务器端【"+s.getLocalAddress().getHostAddress()+"::"+s.getLocalPort()+"】!");
dos.flush();
dos.close();
s.close();
}
}
}
运行结果:
上客户端程序:
TestTCPClient
package socketdemo;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class TestTCPClient {
public static void main(String[] args)throws IOException {
for(int i =0;i<5;i++){
Socket s = new Socket("192.168.0.2",9999);
// ------------------------------------------
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("接收:"+dis.readUTF());
dis.close();
// ------------------------------------------
s.close();
}
}
}
运行结果:
(客户端)
(服务器端)
posted on 2010-11-12 23:57
Mineralwasser 阅读(204)
评论(0) 编辑 收藏