socket接口demo代码直接贴
client端
package com.hbis.modules.socket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import com.hbis.modules.util.BaseUtil;
public class Client2 {
public static final String IP_ADDR = "127.0.0.1";//服务器地址
public static final int PORT = 12000;//服务器端口号
@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws Exception {
Socket socket = new Socket(IP_ADDR, PORT);
//创建一个流套接字并将其连接到指定主机上的指定端口号
//向服务器端发送数据
for(int i =0;i < 20;i++) {
OutputStream out = socket.getOutputStream();
String s = "ARE_YOU_THERE@";
out.write(s.getBytes());
//out.flush();//需要不停的发送心跳是打开
//如果对方有回传信息的话打开下方注释代码
// InputStream in = socket.getInputStream();
// int len = 0;
// byte [] buf = new byte[1024];
// while((len = in.read(buf)) != -1) {
// String bufString = new String(buf);
// System.out.println(bufString);
// break;
// }
/**
*也可以使用字符流的方式
**/
// BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//
// System.out.println("Server回复的消息: " + in.readLine());
// out.close();
}
}
}
server端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
public class ServerThread implements Runnable {
// 和本线程相关的Socket
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
public ThreadLocal<String> threadLocal = new ThreadLocal<String>();
@Override
public void run() {
while(true) {
try {
InputStream in = socket.getInputStream();
@SuppressWarnings("unused")
int len = 0;
byte[] buf = new byte[1024];
//把字节全部读到byte[] buf里面
int index = 0;
String bufString = "";
while ((len = in.read(buf)) != -1) {
bufString = new String(buf);
break;
}
if("ARE_YOU_THERE@".equals(bufString.trim())) {
OutputStream out = socket.getOutputStream();
String s = "I_AM_HERE@ ";
out.write(s.getBytes());
//可以用字符流的方式,会比字节流读取更快一些
// PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// out.println("I_AM_HERE@NULL");
}
} catch (Exception e) {
try {
this.socket.close();
break;
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}