socket

Posted joyous

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket相关的知识,希望对你有一定的参考价值。

server

package socket_server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyService {
public static void main(String[] args) {
try {
ServerSocket s=new ServerSocket(8888);
Socket s1=s.accept();
InputStream inp = s1.getInputStream();
OutputStream out = s1.getOutputStream();
byte[] b=new byte[1024];
int len =-1;
len =inp.read(b);
String str=new String(b, 0, len);
if(str.equals("ok")){
out.write("好好考试,争取被录取".getBytes());
}
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

client

package socket_client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClient {
public static void main(String[] args) {
try {
Socket s=new Socket("192.168.74.179",8888);
InputStream inp = s.getInputStream();
OutputStream out = s.getOutputStream();
out.write("ok".getBytes());
byte[] b=new byte[1024];
int len=-1;
len=inp.read(b);
String str =new String(b, 0, len);
System.out.println(str);
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

以上是关于socket的主要内容,如果未能解决你的问题,请参考以下文章

socket通信

java实例检查端口是否被占用

网络通信与Socket

分布式理论,架构设计Socket和IO模型

分布式理论,架构设计Socket和IO模型

android做一个简单上传文件的功能,socket连接问题