package javaSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
//Socket s=null;
public static void main(String args[]){
int count=0;
//Socket s;
try {
ServerSocket sever=new ServerSocket(8888);
System.out.println("----------服务器已经启动正在等待连接-----------");
while(true){
Socket s=sever.accept();
ThreadSever th=new ThreadSever(s);
th.run();
count++;
System.out.println("第"+count+"个用户已登录!");
InetAddress address=s.getInetAddress();
System.out.println("当前用户的主机为:"+address.getHostName());
}
/* InputStream severin=s.getInputStream();
BufferedReader bw=new BufferedReader(new InputStreamReader(severin));
String data;
while((data=bw.readLine())!=null){
System.out.println(data);
}
s.shutdownInput();
OutputStream severout=s.getOutputStream();
PrintWriter pw=new PrintWriter(severout);
pw.write("------登陆成功!欢迎您!-------");
pw.flush();
s.shutdownOutput();
severin.close();
bw.close();
severout.close();
pw.close();*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
------------------------------------------------
package javaSocket;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;
public class Client{
public static void main(String[] args) throws Exception {
Socket s=new Socket("LocalHost",8888);
OutputStream clientout=s.getOutputStream();
PrintWriter pw=new PrintWriter(clientout);
pw.write("姓名:xiesai,密码:123");
pw.flush();
s.shutdownOutput();
InputStream clientin=s.getInputStream();
BufferedReader bw=new BufferedReader(new InputStreamReader(clientin));
String data;
while((data=bw.readLine())!=null){
System.out.println(data);
}
s.shutdownInput();
clientout.close();
pw.close();
clientin.close();
bw.close();
}
}
------------------------------------------------
package javaSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class ThreadSever extends Thread {
Socket s;
public ThreadSever(Socket socket){
this.s=socket;
}
public void run(){
try {
InputStream severin=s.getInputStream();
BufferedReader bw=new BufferedReader(new InputStreamReader(severin));
String data;
while((data=bw.readLine())!=null){
System.out.println(data);
}
s.shutdownInput();
OutputStream severout=s.getOutputStream();
PrintWriter pw=new PrintWriter(severout);
pw.write("------登陆成功!欢迎您!-------");
pw.flush();
s.shutdownOutput();
severin.close();
bw.close();
severout.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java入门之Socket通信
最新推荐文章于 2024-08-23 15:54:50 发布