描述:启动服务器端,客户端连接服务器端成功之后,服务器端发送“你好,我是服务器,欢迎你的到来!”,客户端发送“你好,我是客户端!”
package com.java.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
System.out.println("服务器准备启动..., 等待客户端的连接...");
ServerSocket ss = new ServerSocket(2002);
//while(true){
Socket socket = ss.accept();
System.out.println(socket);
Thread thread = new Thread(new MyRunnable(socket));
thread.start();
//}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.java.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MyRunnable implements Runnable {
private Socket socket;
public MyRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
InputStream inStream = null;
OutputStream outStream = null;
int count = 0;
try{
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
count = inStream.available();
byte[] strByte = new byte[count];
inStream.read(strByte);
System.out.println(new String(strByte));
String outStr = "你好,我是服务器,欢迎你的到来!";
outStream.write(outStr.getBytes());
outStream.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
try {
if(inStream != null){
inStream.close();
}
if(outStream != null){
outStream.close();
}
if(socket != null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.java.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 2002);
socket.setKeepAlive(true);
socket.setSoTimeout(30*1000);
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
String outStr = "你好,我是客户端!";
outStream.write(outStr.getBytes());
outStream.flush();
socket.shutdownOutput();
InputStreamReader isr = new InputStreamReader(inStream);
BufferedReader br = new BufferedReader(isr);
String str = null;
while((str = br.readLine()) != null){
System.out.println(str);
}
inStream.close();
outStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:
server端:
服务器准备启动..., 等待客户端的连接...
Socket[addr=/127.0.0.1,port=55204,localport=2002]
你好,我是客户端!
client端:
你好,我是服务器,欢迎你的到来!