serverDemo
package cn.stat.p4.ipdemo; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class serverDemo { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//创建服务器对像
ServerSocket ss=new ServerSocket(1000);
//获取连接过来的客户端对像
Socket s=ss.accept(); String ip=s.getInetAddress().getHostAddress();
int port=s.getPort(); //通过socket对象获取输入流,要读取客户端发过来的数据
InputStream in=s.getInputStream(); byte[] buf=new byte[1024]; int len=in.read(buf);
String text=new String(buf,0,len);
System.out.println(ip+":"+port+":"+text); //使用客户端的socket对象传输数据回客户端
OutputStream out=s.getOutputStream();
out.write("收到".getBytes()); s.close();
ss.close(); } }
clentDemo
package cn.stat.p4.ipdemo; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException; public class clentDemo { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
//创建连接对像
Socket socket=new Socket("192.168.1.103",1000);
//获取流对像
OutputStream out=socket.getOutputStream(); out.write("我又来了".getBytes()); //读取服务端返回数据
InputStream in=socket.getInputStream();
byte[] buf=new byte[1024]; int len=in.read(buf); String text=new String(buf,0,len);
System.out.println(text); socket.close(); } }