server
package socket_server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;public class MyService {
public static void main(String[] args) {
try {
ServerSocket s=new ServerSocket(8888);
Socket s1=s.accept();
InputStream inp = s1.getInputStream();
OutputStream out = s1.getOutputStream();
byte[] b=new byte[1024];
int len =-1;
len =inp.read(b);
String str=new String(b, 0, len);
if(str.equals("ok")){
out.write("好好考试,争取被录取".getBytes());
}
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client
package socket_client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;public class MyClient {
public static void main(String[] args) {
try {
Socket s=new Socket("192.168.74.179",8888);
InputStream inp = s.getInputStream();
OutputStream out = s.getOutputStream();
out.write("ok".getBytes());
byte[] b=new byte[1024];
int len=-1;
len=inp.read(b);
String str =new String(b, 0, len);
System.out.println(str);
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}