服务器
public class SimpleServer extends Thread{
private ServerSocket serverSocket;
public SimpleServer(int port) throws IOException{
//类被实例化,服务器被创建
serverSocket=new ServerSocket(port);
//异常
// serverSocket.setSoTimeout(10000);
}
@Override
public void run() {
while(true){
try {
Socket socket=serverSocket.accept();
// /打印谁连接了我们的服务器
// PrintWriter printWriter=new PrintWriter(socket.getOutputStream());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
out.writeUTF("我是服务器,你来干什么");
DataInputStream dis=new DataInputStream(socket.getInputStream());
String s=dis.readUTF();
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
Thread thread=new SimpleServer(9000);
thread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客服端
public class SimpleClient {
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost", 9000);
//接受服务区信息
DataInputStream inputStream=new DataInputStream(socket.getInputStream());
String s=inputStream.readUTF();
System.out.println(s);//打印服务器的信息
//客户机发送信息到服务器
DataOutputStream input=new DataOutputStream(socket.getOutputStream());
input.writeUTF("我是小黑,我来找你,服务器你好");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}