本人新人程序员,第一次写博客,若有错误之处感谢指正。
客户端代码,SERVERIP是本机,向服务器发送hello字符串并打印返回的信息。
public class socket {
private static final String SERVERIP = "127.0.0.1";
private static final int PORT = 4546;
private InputStream is=null;
private OutputStream os=null;
private Socket socket=null;
public socket(){
try {
socket = new Socket(SERVERIP,PORT);
is = socket.getInputStream();
os = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMsg(){
String s = "hello";
byte b[] = new byte[1024];
try {
os.write(s.getBytes());
int n = is.read(b);
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
private void close(){
try {
os.close();
is.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端代码,采用单例模式初始化ServerSocket,并使用无线循环接受客户端Socket,接收到后开启一个线程去处理。
class serverSocket {
private static serverSocket serverSocket =null;
private static final int port = 4546;
private Socket socket=null;
private ServerSocket ss=null;
private serverSocket(){
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static serverSocket getServerSocket(){
if(null==serverSocket){
serverSocket = new serverSocket();
}
return serverSocket;
}
public void getConn(){
while (true){
try {
socket = ss.accept();
new SocketThread(socket);
} catch (IOException e) {
e.printStackTrace();
服务端处理线程,接受来自客户端的信回给客户端“I accept”信息,最后关闭资源。
public class SocketThread extends Thread {
private Socket socket=null;
private InputStream is=null;
private OutputStream os=null;
public SocketThread(Socket socket){
this.socket=socket;
this.start();
}
@Override
public void run() {
byte b[] = new byte[1024];
int n=0;
String s = "I accepted.";
try {
is = socket.getInputStream();
os = socket.getOutputStream();
if((n=is.read(b))!=-1){
System.out.println(new String(b));
os.write(s.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
priva
is.close();
socket.close();
}
}
os.close();is.close();
socket.close();
}
}