编写TCP通信程序,服务器端发送字符串到客户端。
ReadClient.java
//ReadClient.java
import java.io.*;
import java.net.*;
public class ReadClient {
public static void main(String args[]) throws IOException {
Socket clientSocket = null;
DataOutputStream outbound = null;
DataInputStream inbound = null;
InputStreamReader inS = null;
try {
// 与服务器建立连接
clientSocket = new Socket("10.10.49.47", 80); // IP地址:10.10.49.47
System.out.println("Client1: " + clientSocket);
// 初始化流对象
outbound = new DataOutputStream(clientSocket.getOutputStream());
inbound = new DataInputStream(clientSocket.getInputStream());
inS = new InputStreamReader(inbound);
// 发送数据
outbound.writeBytes("hello\r\n");
System.out.println("hello"); // 客户端输出"hello"字符串
outbound.flush();
int c;
while ((c = inS.read()) != -1) {
System.out.print((char) c);
}
} catch (UnknownHostException uhe) {
System.out.println("UnknownHostException: " + uhe);
}
catch (IOException ioe) {
System.err.println("IOException: " + ioe);
} finally {
// 关闭流及clientSocket
inS.close();
outbound.close();
inbound.close();
clientSocket.close();
}
}
}
SimpleWebServer.java
//SimpleWebServer.java
import java.io.*;
import java.net.*;
public class SimpleWebServer {
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
int connects = 0;
try {
// 创建服务器Socket,端口80,限制5个连接
serverSocket = new ServerSocket(80, 5);
while (connects < 5) {
// 等待连接
clientSocket = serverSocket.accept();
// 操作连接
ServiceClient(clientSocket);
connects++;
}
serverSocket.close();
}
catch (IOException ioe) {
System.out.println("Errorin SimpleWebServer: " + ioe);
}
}
public static void ServiceClient(Socket client) throws IOException {
DataInputStream inbound = null;
DataOutputStream outbound = null;
try {
// 获取输入输出流
inbound = new DataInputStream(client.getInputStream());
outbound = new DataOutputStream(client.getOutputStream());
StringBuffer buffer = new StringBuffer(
"\"http://www.ytu.edu.cn/\"\r\n");
String inputLine;
while ((inputLine = inbound.readLine()) != null) {
// 判断输入为Hello时,输出字符串
if (inputLine.equals("hello")) {
outbound.writeBytes(buffer.toString());
break;
}
}
} finally {
// 打印清除连接,关闭流及Socket
System.out.println("Cleaningup connection: " + client);
outbound.close();
inbound.close();
client.close();
}
}
}
运行结果:
注意:
Address already in use: JVM_Bind 错误 为端口冲突,改变Socket端口直到成功;
变量声明在try外面,main函数里面,否则finally关闭流及Socket 时会出现 变量cannot be resolved 错误;
Unhandled exception type IOException 错误为 未抛出异常,main函数发现错误抛出即可。