做一个两边能对话的程序,当其中一个写出886是停止,目前有缺陷,只能一人一句的对话,以后也许会进一步修改
Send类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Send {
public static void main(String[] args) throws IOException {
Socket s=new Socket("192.168.1.1",11111);
Scanner sc=new Scanner(System.in);
while(true){
System.out.print("我:");
String str=sc.nextLine();
byte[] bye=str.getBytes();
OutputStream os=s.getOutputStream();
if(str.equals("886")){
os.write(bye);
return;
}else{
os.write(bye);
}
InputStream is=s.getInputStream();
byte[] bytes=new byte[1024];
int len=is.read(bytes);
String data=new String(bytes,0,len);
if(data.equals("886")){
System.out.println("他:"+data);
return;
}else{
System.out.println("他:"+data);
}
}
}
}
Receive类
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 Receive {
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(11111);
Socket s=ss.accept();
while(true){
InputStream is=s.getInputStream();
byte[] bye=new byte[1024];
int len=is.read(bye);
String data=new String(bye,0,len);
if(data.equals("886")){
System.out.println("他:"+data);
return;
}else{
System.out.println("他:"+data);
}
OutputStream os=s.getOutputStream();
Scanner sc=new Scanner(System.in);
System.out.print("我:");
String str=sc.nextLine();
byte[] bytes=str.getBytes();
if(str.equals("886")){
os.write(bytes);
return;
}else{
os.write(bytes);
}
}
}
}
运行结果
实在想不出什么有趣的对话,就这吧!!!



