服务器:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; public class TcpServer {
public static void main(String [] args) throws IOException
{
@SuppressWarnings("resource")
ServerSocket server=new ServerSocket(8000);
Socket s=null;
DataOutputStream dataOut=null;
DataInputStream dataIn=null;
while(true){
try{
s=server.accept();
dataOut=new DataOutputStream(s.getOutputStream());
dataIn =new DataInputStream(s.getInputStream());
while(true){
Byte c=dataIn.readByte();
if(c=='0'){
System.out.println("执行继电器快关变换!");
dataOut.writeByte('Y');
}else if(c=='w'){
System.out.println("将温度值传给服务器!");
dataOut.writeByte(2);
}else if(c=='s'){
System.out.println("将深度值传给服务器!");
dataOut.writeByte(4);
}else{
System.out.println("错误命令返回!");
dataOut.writeByte('N');
}
}
}catch(IOException e){}
dataOut.close();
dataIn.close();
s.close();
}
}
}
客户端代码:
/*
TCP客户端:输入命令从服务器获得数据
输入:0即开关继电器,当服务器执行好任务时返回89
w获得温度数据,服务器返回温度数据
s获得水深数据,服务器返回水深数据
其他输入均为无效输入,服务器返回78
PS:服务器只接受1个char,返回也是一个char,上述数据均为16进制
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner; public class TcpClient {
public static void main(String [] args) throws IOException
{
Socket s = null;
DataInputStream DataIn = null;
DataOutputStream DataOut = null;
try {
//s=new Socket(InetAddress.getByName("192.168.1.130"),8000);
s=new Socket("localhost",8000);
DataIn = new DataInputStream(s.getInputStream());
DataOut=new DataOutputStream(s.getOutputStream());
System.out.println("连接成功");
@SuppressWarnings("resource")
Scanner keyIn= new Scanner(System.in);
while(keyIn.hasNext()){
String c=keyIn.nextLine();
System.out.println("输入: "+c);
if(c.length()==0)continue;
DataOut.writeByte(c.charAt(0));
System.out.println("收到: "+DataIn.readByte());
}
DataIn.close();
DataOut.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataIn.close();
DataOut.close();
s.close();
}
}