62,614
社区成员
发帖
与我相关
我的任务
分享
public class SocketMain {
public static void main(String[] args) {
Socket socket = null;
OutputStream output = null;
InputStream input = null;
int read;
ByteArrayOutputStream byteOutput = null;
String result = null;
try {
socket = new Socket("localhost", 8888);
output = socket.getOutputStream();
input = socket.getInputStream();
// - 请求
output.write("这里是CSDN论坛!".getBytes());
output.flush();
byteOutput = new ByteArrayOutputStream();
while((read = input.read()) != -1){
byteOutput.write(read);
}
// - 响应
result = new String(byteOutput.toByteArray(),"GBK");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(output != null){
output.close();
}
if(input != null){
input.close();
}
if(byteOutput != null){
byteOutput.close();
}
if(socket != null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result);
}
}
public class ServerSocketMain {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
OutputStream output = null;
InputStream input = null;
ByteArrayOutputStream byteOutput = null;
int read = 0;
String result = null;
byte[] bytes = null;
try {
serverSocket = new ServerSocket(8888);
while(true){
/*
* 循环内收到一个请求并处理完之后,必须将socket和output和input关掉,
* 下次收到请求时,再打开一个socket、output和input
*/
try{
socket = serverSocket.accept();
output = socket.getOutputStream();
input = socket.getInputStream();
// - 接收
byteOutput = new ByteArrayOutputStream();
int i=0;
while(true){
i++;
read = input.read();
System.out.println(read);
if(i > 100){
break;
}
byteOutput.write(read);
}
result = new String(byteOutput.toByteArray(), "GBK");
// bytes = new byte[1000];
// input.read(bytes);
// result = new String(bytes, "GBK");
System.out.println(result);
// - 反馈
output.write("郝彬彬先生,您好!".getBytes());
output.flush();
} catch (IOException e){
e.printStackTrace();
} finally {
try {
if(output != null){
output.close();
}
if(input != null){
input.close();
}
if(byteOutput != null){
byteOutput.close();
}
if(socket != null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(serverSocket != null){
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
while(true){
read = input.read(bytes);
if(read == -1){
break;
}
result = new String(bytes, "GBK");
System.out.println(result);
}