TCP
客户端:
System.out.println("客户端:");
Socket sck = new Socket("192.168.0.3",1);
//向服务器端发消息
OutputStream out = sck.getOutputStream();
out.write("woshihaoren".getBytes());
//接受服务器端发来的消息
InputStream in = sck.getInputStream();
byte[] b = new byte[1024];
int i = in.read(b);
System.out.println(new String(b,0,i));
sck.close();
服务器端:
System.out.println("服务端");
ServerSocket ssckt = new ServerSocket(1);
//获得客户端对象
Socket sckt = ssckt.accept();
//接受客户端发来的消息
InputStream in = sckt.getInputStream();
byte[] b = new byte[1024];
int i = in.read(b);
System.out.println(new String(b,0,i));
//向客户端发送消息
OutputStream ops = sckt.getOutputStream();
ops.write("我是服务器".getBytes());
ssckt.close();
客户端:
System.out.println("客户端:");
Socket sck = new Socket("192.168.0.3",1);
//向服务器端发消息
OutputStream out = sck.getOutputStream();
out.write("woshihaoren".getBytes());
//接受服务器端发来的消息
InputStream in = sck.getInputStream();
byte[] b = new byte[1024];
int i = in.read(b);
System.out.println(new String(b,0,i));
sck.close();
服务器端:
System.out.println("服务端");
ServerSocket ssckt = new ServerSocket(1);
//获得客户端对象
Socket sckt = ssckt.accept();
//接受客户端发来的消息
InputStream in = sckt.getInputStream();
byte[] b = new byte[1024];
int i = in.read(b);
System.out.println(new String(b,0,i));
//向客户端发送消息
OutputStream ops = sckt.getOutputStream();
ops.write("我是服务器".getBytes());
ssckt.close();