读书人

问几个很简单的有关问题

发布时间: 2012-01-05 22:36:54 作者: rapoo

问几个很简单的问题
先贴一段程序.很简单的,有几个问题要请教大家,谢谢


实现Client端功能的ClientApp.java原文件:

import java.net.*;
import java.io.*;
import java.lang.*;

public class ClientApp
{
public static void main(String args[])
{
try
{
//创建通讯并且和主机Rock连接
Socket cSocket=new Socket( "192.168.100.188 ",8018);
//打开这个Socket的输入/输出流
OutputStream os=cSocket.getOutputStream();
DataInputStream is=new DataInputStream(cSocket.getInputStream());

int c;
boolean flag=true;

String responseline;

while(flag)
{
//从标准输入输出接受字符并且写如系统
while((c=System.in.read())!=-1)
{
os.write((byte)c);
if(c== '\n ')
{
os.flush();
//将程序阻塞,直到回答信息被收到后将他们在标准输出上显示出来
responseline=is.readLine();
System.out.println( "Message is: "+responseline);
}
}
}
os.close();
is.close();
cSocket.close();

}
catch(Exception e)
{
System.out.println( "Exception : "+ e.getMessage());
}
}
}


实现Server端功能的ServerApp.java原文件:

import java.net.*;
import java.io.*;

public class ServerApp
{
public static void main(String args[])
{
try


{
boolean flag=true;
Socket clientSocket=null;
String inputLine;
int c;

ServerSocket sSocket=new ServerSocket(8018);
System.out.println( "Server listen on: "+sSocket.getLocalPort());

while(flag)
{
clientSocket=sSocket.accept();
DataInputStream is= new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
OutputStream os=clientSocket.getOutputStream();

while((inputLine=is.readLine())!=null)
{
//当客户端输入stop的时候服务器程序运行终止!
if(inputLine.equals( "stop "))
{
flag=false;
break;
}
else
{
System.out.println(inputLine);

while((c=System.in.read())!=-1)
{
os.write((byte)c);
if(c== '\n ')
{
os.flush(); //将信息发送到客户端
break;
}


}
}


}
is.close();
os.close();
clientSocket.close();

}
sSocket.close();
}
catch(Exception e)
{
System.out.println( "Exception : "+ e.getMessage());
}
}
}




[解决办法]
我简单举个例子
public abstarct class First{

}//一个抽象类
public class Second extends First
{
}
这分别是两个类的定义,First相当于OutputStream,而Second相当于OutputStream的之类
然后在其他类中应用
public class Test
{
public void use()
{ First a=this.getFirst();//

}

public static First getFirst()
{
Second a=new Second();
return (First)a;//实际返回的a是First的子类Second类
}
}

读书人网 >J2SE开发

热点推荐