服务端程序:
public class Demo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
try {
ServerSocket server =new ServerSocket(6666);
Socket client = null;
int i=0;
while(true) {
client = server.accept();
new Thread(new ServerThread(client)).start();
i++;
System.out.println("当前是第:"+i+"个用户连进来了。接入的客户端的IP地址:"+client.getInetAddress().getHostAddress());
}
} catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }
}
class ServerThread implements Runnable{
Socket client =null;
ServerThread(Socket temp){
this.client=temp;
}
@Override
public void run() {
// TODO 自动生成的方法存根
try {
InputStream in = client.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader buff = new BufferedReader(reader);
String str="";
while((str=buff.readLine())!=null){
System.out.println("接受到客户端请求:"+str);
}
client.shutdownInput();
OutputStream out = client.getOutputStream();
PrintWriter p = new PrintWriter(out);
p.write("欢迎您");
p.flush();
reader.close();
in.close();
p.close();
out.close();
client.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
客户端程序:
public class Demo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
try {
Socket client =new Socket(InetAddress.getLocalHost(),6666);
OutputStream out = client.getOutputStream();
String str="登录名:张三 密码:123";
out.write(str.getBytes());
out.flush();
client.shutdownOutput();
InputStream in = client.getInputStream();
InputStreamReader reader =new InputStreamReader(in);
BufferedReader buff =new BufferedReader(reader);
String request="";
while((request=buff.readLine())!=null) {
System.out.println("获取服务端返回:"+request);
}
out.close();
reader.close();
in.close();
client.close();
} catch (UnknownHostException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} }