/**
* Description: 客户端
* Copyright (c) , 2016, Jansonxu
* This program is protected by copyright laws.
* Program Name:Client.java
* Date: 2016年1月26日
*
* @author 李阳
* @version : 1.0
*/
package ChatOnline;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Socket client=null;
Scanner input=null;
try {
client=new Socket(“localhost”,9999);
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
input=new Scanner(System.in);
while(true){
System.out.println(“you say “);
String infotoserver=input.nextLine();
os.write(infotoserver.getBytes());
os.flush();
//判断用户是否退出聊天
if(“886”.equals(infotoserver)){
break;
}
//走到这证明不是 886
//读取来自服务器
byte[] b=new byte[1024];//516个汉子
int len=is.read(b);
System.out.println(“服务器说”+new String(b,0,len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(client!=null){
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}if(input!=null){
input.close();
}
}
}
}
/**
* Description: 聊天服务器端
* Copyright (c) , 2016, Jansonxu
* This program is protected by copyright laws.
* Program Name:Server.java
* Date: 2016年1月26日
*
* @author 李阳
* @version : 1.0
*/
package ChatOnline;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
@SuppressWarnings(“resource”)
public static void main(String[] args) {
try {
Server instance=new Server();
ServerSocket server=new ServerSocket(9999);
//通过循环为不同的客户端提供服务
while(true){
Socket client=server.accept();
new Thread(instance.new ServiceThread(client)).start();
//instance.servicalFor(client);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServiceThread implements Runnable{
private Socket client;
public ServiceThread(Socket client) {
super();
this.client = client;
}
@SuppressWarnings("resource")
@Override
public void run() {
try {
InputStream is=client.getInputStream();
OutputStream os=client.getOutputStream();
Scanner input=new Scanner(System.in);
while(true){
byte[] b=new byte[1024];
int len=is.read(b);
String info=new String(b,0,len);
System.out.println("苍井空: "+info);
if("886".equals(info)){
break;
}
System.out.println("颜克亮说");
String info1=input.nextLine();
os.write(info1.getBytes());
os.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(client!=null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}