TCP客户端:
public static void main(String args[]) throws IOException
{
Socket s=new Socket("127.0.0.1",10001);
OutputStream os=s.getOutputStream();
os.write("哈哈".getBytes());
InputStream in=s.getInputStream();
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1)
{
System.out.println(new String(buf,0,len));
}
s.close();
}
TCP服务端:
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(10001);
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"....connect");
InputStream in=s.getInputStream();
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1)
{
System.out.println(new String(buf,0,len));
}
OutputStream os=s.getOutputStream();
os.write("haha".getBytes());
s.close();
ss.close();
} |
|