public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1",6666);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("客户端的信息来了");
pw.flush();
socket.shutdownOutput();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(isr);
String info = null;
while ((info=br.readLine())!=null) {
System.out.println(info);
}
socket.shutdownInput();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 服务器端
*
* @author Administrator
*
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器开始监听了啊");
Socket socket = null;
int count = 0;
while (true) {
socket = serverSocket.accept();
ServerThread st = new ServerThread(socket);
st.setPriority(4);
st.start();
InetAddress ia = socket.getInetAddress();
count++;
System.out.println("第"+count+"个客户端");
System.out.println("IP地址"+ia.getHostAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ServerThread extends Thread {
public Socket socket;
public ServerThread(Socket socket){
this.socket = socket;
}
@Override
public void run() {
InputStream is =null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os = null;
PrintWriter pw =null;
try {
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String data =null;
while((data=br.readLine())!=null){
System.out.println(data);
}
socket.shutdownInput();
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("服务器说:给你会消息了");
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(os!=null){
os.close();
}
if(br!=null){
br.close();
}
if(isr!=null){
isr.close();
}
if(is!=null){
is.close();
}
if(socket!=null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}