http://wonka438.iteye.com/blog/1279136
使用java建立基于socket的c/s接收系统
//运行时输入端口
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class TCPEchoServer
{
/**
* @param args
*/
private static final int BUFSIZE = 32;
public static void main(String[] args) throws IOException
{
if (args.length != 1)//获取启动服务的端口
throw new IllegalArgumentException("Parameter(s): ");
int servPort = Integer.parseInt(args[0]);
//分配一个端口用于启动server端
ServerSocket servSock = new ServerSocket(servPort);
int recvMsgSize;
byte[] receiveBuf = new byte[BUFSIZE];
while (1)
{
Socket clntSock = servSock.accept(); //接收客户端的主动连接
SocketAddress clientAddress = clntSock.getRemoteSocketAddress();
System.out.println("Handling client at " + clientAddress);
InputStream in = clntSock.getInputStream();
OutputStream out = clntSock.getOutputStream();
while ((recvMsgSize = in.read(receiveBuf)) != -1)
{
out.write(receiveBuf, 0, recvMsgSize);
}
clntSock.close();
}
}
}
//运行时输入 连接地址 字符 端口
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
public class TCPEchoClient
{
public static void main(String[] args) throws IOException
{
if ((args.length < 2) || (args.length > 3)) // 传入的数据在2~3之间,0:地址 1:传输字符 <2:端口>
throw new IllegalArgumentException("Parameter(s): []");
String server = args[0]; // ip地址或主机名称
byte[] data = args[1].getBytes();
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;//默认端口为7
Socket socket = new Socket(server, servPort);
System.out.println("Connected to server...sending echo string");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(data);
int totalBytesRcvd = 0;
int bytesRcvd;
while (totalBytesRcvd < data.length) {
if ((bytesRcvd = in.read(data, totalBytesRcvd,data.length - totalBytesRcvd)) == -1)
throw new SocketException("Connection closed prematurely");
totalBytesRcvd += bytesRcvd;
}
System.out.println("Received: " + new String(data));
socket.close();
}
}