ServiceDemo,ClientDemo Socket chat

ServiceDemo:

package com.demo.service;

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 ServiceDemo {




public static void main(String[] args) {
try {
new ServiceDemo().service();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void service() throws IOException{
ServerSocket server=new ServerSocket(800);
while(true){
System.out.println("正在等待客户端连接");
Socket so =server.accept();//监听客户端连接
new Server(so).start();
//System.out.println("客户端连接成功");

}
}

class Server extends Thread{

private Socket so;


public Server(Socket so) {

this.so = so;
}


@Override
public void run() {
InputStream in=null;//in 接收
OutputStream out=null;//out 发送

try {
in=so.getInputStream();
out=so.getOutputStream();

String str="你吃早餐了吗";
out.write(str.getBytes());
out.write('\n');
out.flush();

//接收客户端发送来的数据
Scanner scan=new Scanner(in);
while(true){
//读取客户端发送过来的一行数据并去掉空格
String sentStr=scan.nextLine().trim();
if(sentStr.equals("我吃了")){
out.write("你吃的什么".getBytes());
out.write('\n');
out.flush();
}else if(sentStr.equals("吃的包子")){
out.write("早餐还不错".getBytes());
out.write('\n');
out.flush();
}else{
out.write("你会不会聊天".getBytes());
out.write('\n');
out.flush();
break;
}
}
so.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


}

ClientDemo  :

package com.demo.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientDemo {

public static void main(String[] args) {

try {
new ClientDemo().client();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public void client() throws UnknownHostException, IOException{
Socket so=new Socket("localhost",800);
InputStream in=so.getInputStream();
OutputStream out=so.getOutputStream();

new Reader(out).start();
new Writer(in).start();
}

//读取控制台,往服务器端写
class Reader extends Thread{
private OutputStream out;

public Reader(OutputStream out) {
super();
this.out = out;
}

@Override
public void run() {
Scanner scan=new Scanner(System.in);
while(true){
String str=scan.nextLine().trim();
try {
out.write(str.getBytes());
out.write('\n');
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



}

//读取服务器端发送来的数据
class Writer extends Thread{
private InputStream in;


public Writer(InputStream in) {
super();
this.in = in;
}


@Override
public void run() {
int x=0;
try {
while((x=in.read())!=-1){
System.out.write(x);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
}

posted on 2016-07-27 22:00  yang32  阅读(87)  评论(0编辑  收藏  举报

导航