日期:2014-05-20  浏览次数:20700 次

寻求简单通讯的例子



要求tcp/ip同步短连接
即:
          客户端发送信息时连接,得到服务响应(信息的返回,问题的回答等等)客户端中止连接。
再发送时重新连接。


-----------------告急--------------

------解决方案--------------------
服务端:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleTestServer {
public static void main(String[] args) {
try {
ServerSocket ssocket = new ServerSocket(2000);
//port
while (true) {
Socket socket = ssocket.accept();
socket.setSoTimeout(0);
DataInputStream dataIn = new DataInputStream(socket
.getInputStream());
byte[] readBytes = new byte[1000];
int length = dataIn.read(readBytes);
if (length == -1) {
break;
}
/**
* 处理请求,比如打印收到的信息。
*/
System.out.println(new String(readBytes,0,length));
/**
* 构造应答信息
*/
byte[] reply = new byte[] { 'r ', 'e ', 'p ', 'l ', 'y ' };
DataOutputStream dataOut = new DataOutputStream(socket
.getOutputStream());
/**
* 发送应答信息
*/
dataOut.write(reply);
dataOut.flush();
dataOut.close();
/**
* 关闭连接
*/
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

客户端:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SimpleTestClient {
public static void main(String[] args) {
try
{
Socket socket = new Socket( "127.0.0.1 ",2000);
//ip port
socket.setSoTimeout(0);
DataOutputStream dataOut = new DataOutputStream(socket
.getOutputStream());
byte[] requestBytes=new byte[]{ 'r ', 'e ', 'q ', 'u ', 'e ', 's ', 't '};
dataOut.write(requestBytes);
dataOut.flush();
DataInputStream dataIn = new DataInputStream(socket
.getInputStream());
byte[] readBytes = new byte[1000];
int length = dataIn.read(readBytes);
dataIn.close();
if(length==-1)
{
dataOut.close();
socket.close();
}
System.out.println(new String(readBytes,0,length));
dataOut.close();
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}