Socket和ServerSocket通信例子

来源:互联网 发布:java面试题大全带答案 编辑:程序博客网 时间:2024/05/19 10:38

Socket-->dataOutputStream(dops)--->dops.writeUTF("nb")--->dataInputStream(dips)--->dips.read("NB");

ServerSocket--->dataInputStream(dips)--->dips.read("nb")--->dataOutputStream(dops)--->dops.writeUTF("NB");

Demo--->

client--->

Socket s=new Socket("localhost",8989);

DataOutputStream dos=new DataOutputStream();

DataInputStream dis=new DataInputStream();

Scanner sca=new Scanner(System.in);

String in=sca.next("nb");

dos.writeUTF(in);

byte[] b=new byte[1024];

int len=dis.read(b);

String str=new String(b,0,len);

dis.read(str);

dos.close();

dis.close();

s.close();

sca.close();

server--->

ServerSocket ss=new ServerSocket(8989);

Socket s=ss.accept();

DataOutputStream dos=new DataOutputStream();

DataInputStream dis=new DataInputStream();

byte[] b=new byte[1024];

int len=dis.read(b);

String str=new String(b,0,len);

dos.write(str.toUpperCase());

dos.close();

dis.close();

s.close();

原创粉丝点击