写了个socket小程序, 先放在这 以后来改进
看到一个很好的例子:http://cuisuqiang.iteye.com/blog/1489661
1.服务端
package Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
ServerSocket ss = null;
public Server(int port) throws IOException
{
ss = new ServerSocket(port);
}
public void listen()
{
Socket socket = null; //短连接 , 用完就关闭 所以不放在类的属性里
while(true)
{
try {
socket = ss.accept();
//System.out.println(socket.hashCode()); //验证socket被子类关闭
new Thread(new ServerImpl(socket)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerImpl implements Runnable
{
Socket client = null;
public ServerImpl(Socket client)
{
this.client = client;
}
public synchronized void run()
{
try {
DataInputStream dis = new DataInputStream(client.getInputStream());
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
String rcv = dis.readUTF();//对应writeUTF() ,避免乱码
System.out.println(rcv);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(client != null)
{
try {
//System.out.println(client.hashCode());//验证关闭父类socket
client.close(); //关闭socket, 子类的client指向父类传来的socket
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
Server server = new Server(8888);
server.listen();
}
}
2.客户端
package Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
Socket socket = null;
public static void main(String[] args) throws IOException {
Client c =new Client();
try {
c.socket = new Socket("127.0.0.1",8888);
DataInputStream dis = new DataInputStream(c.socket.getInputStream());
DataOutputStream dos = new DataOutputStream(c.socket.getOutputStream());
String str = "java-Socket 套接字";
dos.writeUTF(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(c.socket != null)
{
c.socket.close();
}
}
}
}