import java.io.IOException;import java.net.Socket;import java.net.UnknownHostException;public class Client { public static void main(String[] args) throws UnknownHostException, IOException { System.out.println("输入三角形的三边并用逗号隔开,如: (3,4,5) ");byte[] buff=new byte[64];...
java socket网络编程
//==============Server.java=================//
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
System.out.println("服务器就绪,请启动客户端.");
Socket so = s.accept();
byte[] buff = new byte[1024];
int read = so.getInputStream().read(buff);
String[] abc=new String(buff,0,read).split("\\D+");
int a = Integer.parseInt(abc[0]);
int b = Integer.parseInt(abc[1]);
int c = Integer.parseInt(abc[2]);
if(!cbt(a,b,c))
so.getOutputStream().write("输入的数据无法组成三角形.".getBytes());
else
so.getOutputStream().write(getArea(a,b,c).getBytes());
so.getOutputStream().flush();
so.close();
s.close();
}
private static String getArea(int a, int b, int c) {
float s = (a+b+c)/2f;
return "面积: "+Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
private static boolean cbt(int a, int b, int c) {
return a>0&&b>0&&c>0&&a+b>c&&b+c>a&&a+c>b;
}
}
//=================Client.java======================//
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("输入三角形的三边并用逗号隔开,如: (3,4,5) ");
byte[] buff=new byte[64];
int r = System.in.read(buff);
String ipaddr = "localhost";//根据情况改变,在本机调试就不改了
Socket so = new Socket(ipaddr,12345);
so.getOutputStream().write(new String(buff,0,r).getBytes());
r = so.getInputStream().read(buff);
so.close();
String rs = new String(buff,0,r);
System.out.println(rs);
}
}
//先启动Server,再启动Client2009-02-26
设置超时就可以了。然后在cacth能捕捉到2019-04-25
tcp
协议是面向连接的、在这里
设置超时时间就好了2019-05-11
简单!但8高兴写!2009-02-26