[Java] 纯文本查看 复制代码/*
@author Eternity-Myth
@date 2017.9.12
*/
/*导入net包、IO包*/
import java.net.*;
import java.io.*;
/*创建服务器端*/
class TCPServer
{
/*构造trans函数
作用:将客户端传来的信息(字符)变成int类型并返回
*/
private static int trans(String str)
{
try
{
int num = Integer.parseInt(str);
return num;
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) throws Exception
{
//建立服务端socket服务,并监听一个端口
ServerSocket ss=new ServerSocket(6666);
//通过accept方法获取连接过来的客户端对象
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"......connected");
//读取socket读取流中的数据
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
String line=null;
int count=1;//数组下标标识
int num[]=new int[65536];
while((line=bufIn.readLine())!=null)
{
System.out.println(line);//在服务端打印客户端传来的信息
num[count]=trans(line);//转换成int类型后,存储在int数组内
count++;//下标增加,移动到下一位
if(count%2==0)//判断是否是第一个数,如果是,在客户端打印
{
out.println("got the first num: "+num[count-1]);
continue;
}
else//如果是第二个数,在客户端打印,并且打印两个数求和后的结果
{
System.out.println("the sum is: "+(num[count-2]+num[count-1]));
out.println("got the second num: "+num[count-1]+" the sum is: "+(num[count-2]+num[count-1]));
}
}
//关闭资源
s.close();
ss.close();
}
}