用java进行网络编程确实很方便很容易上手这几天用java进行socket编程收获不少
首先进行服务端的编程作为服务端编程主要按下面几个步骤进行
// 创建socket
ServerSocket ss = new ServerSocket(PortNumber);
Socket s = ssaccept(); //监听器产生阻塞直到有连接才停止阻塞
// 打开输入流输出流
OutputStream os = sgetOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
InputStream is = sgetInputStream();
// 根据一定的协议读写数据
// 服务器 > 客户
//oswrite(HelloI am Server!getBytes());
boswrite(HelloI am Server!getBytes());
bosflush(); //注意!!
// 服务器 < 客户
byte[] buf = new byte[];
int len = isread(buf);
Systemoutprintln(new String(buf len));
// 关系流和Socket
//osclose();
bosclose();
isclose();
sclose();
ssclose();
作为客户端则分为下面几个步骤其实和服务端差不多只是少了用ServerSocket进行监听
// 创建socket
Socket s = new Socket(InetAddressgetByName(localhost)
PortNumber);
// 打开输入流输出流
OutputStream os = sgetOutputStream();
InputStream is = sgetInputStream();
// 根据一定的协议读写数据
// 服务器 > 客户
byte[] buf = new byte[];
int len = isread(buf);
Systemoutprintln(new String(buf len));
// 服务器 < 客户
oswrite(HelloI am Client!getBytes());
// 关系流和Socket
osclose();
isclose();
sclose();
上面这些只是一个单线程的服务端>客户端的程序只能进行一次通讯多次通讯将被告知无法连接
这时我们就需要用到进程Thread进行编程将其改造成多线程聊天程序可以同时进行多客户端的连接与发送信息
代码如下
//Serverjava
import javaawt*;
import *;
import javaio*;
public class Server extends Thread {
ServerSocket skt;
Socket Client[]=new Socket[];;
Socket Client=null;
int i = ;
TextArea in;
int portk=l=;
//BufferedReader theInputStream;
PrintStream theOutputStream;
//String readin;
Face chat;
public Server(int port Face chat) {
try {
thisport = port;
skt = new ServerSocket(port);
thischat = chat;
} catch (IOException e) {
chattaappend(etoString());
}
}
public void run() {
chattaappend(等待连线);
while (true) {
//Systemoutprint(+i+\n);
try {
Client[k] = sktaccept(); /* 接收客户连接 */
//当有客户端连接时就新建一个子线程
if (i < ) {
ServerThread server[] = new ServerThread[];
server[k]= new ServerThread(Client[k] thischat i);
l=serverlength;
server[k]start();
chattaappend(客户端 + Client[k]getInetAddress() + 已连线\n);
/*theInputStream = new BufferedReader(new InputStreamReader(Client
getInputStream()));*/
//for(int j=;j<serverlength;j++)
theOutputStream = new PrintStream(server[k]getClient()getOutputStream());
i = server[k]getI();
k++;
} else {
//theOutputStream = new PrintStream(null);
}
} catch (SocketException e) {
//chattaappend(连线中断!\n);
//chatclientBtnsetEnabled(true);
//chatserverBtnsetEnabled(true);
//chattfaddresssetEnabled(true);
//chattfportsetEnabled(true);
//try {
//sktclose();
//Clientclose();
//} catch (IOException err) {
// chattaappend(errtoString());
//}
} catch (IOException e) {
chattaappend(etoString());
}
}
}
public void dataout(String data) {
//for(int j=;j<l;j++)
theOutputStreamprintln(data);
}
}
class ServerThread extends Thread {
ServerSocket skt;
Socket Client;
TextArea in;
int port;
int i;
BufferedReader theInputStream;
PrintStream theOutputStream;
String readin;
Face chat;
//服务端子线程
public ServerThread(Socket s Face chat int i) {
thisi = ++i;
Client = s;
//thisport = port;
//skt = new ServerSocket(port);
thischat = chat;
}
public int getI() {
return thisi;
}
public Socket getClient() {
return thisClient;
}
public void run() {
//chattaappend(等待连线);
try {
//Client = sktaccept(); /* 接收客户连接 */
//chattaappend(客户端 + ClientgetInetAddress() + 已连线\n);
theInputStream = new BufferedReader(new InputStreamReader(Client
getInputStream()));
theOutputStream = new PrintStream(ClientgetOutputStream());
while (true) {
readin = theInputStreamreadLine();
chattaappend(readin + \n);
}
} catch (SocketException e) {
chattaappend(连线中断!\n);
chatclientBtnsetEnabled(true);
chatserverBtnsetEnabled(true);
chattfaddresssetEnabled(true);
chattfportsetEnabled(true);
try {
i;
sktclose();
Clientclose();
} catch (IOException err) {
chattaappend(errtoString());
}
} catch (IOException e) {
chattaappend(etoString());
}
}
public void dataout(String data) {
theOutputStreamprintln(data);
}
}
//Clientjava
import *;
import javaio*;
import javaxswingTimer;
class Client extends Thread {
Socket skt;
InetAddress host;
int port;
BufferedReader theInputStream;
PrintStream theOutputStream;
String readin;
Face chat;
public Client(String ip int p Face chat) {
try {
host = InetAddressgetByName(ip);
port = p;
thischat = chat;
} catch (IOException e) {
chattaappend(etoString());
}
}
public void run() {
try {
chattaappend(尝试连线);
skt = new Socket(host port);
chattaappend(连线成功\n);
theInputStream = new BufferedReader(new InputStreamReader(skt
getInputStream()));
theOutputStream = new PrintStream(sktgetOutputStream());
//Timer myTimer = new Timer();
while (true) {
readin = theInputStreamreadLine();
chattaappend(readin + \n);
}
} catch (SocketException e) {
chattaappend(连线中断!\n);
chatclientBtnsetEnabled(true);
chatserverBtnsetEnabled(true);
chattfaddresssetEnabled(true);
chattfportsetEnabled(true);
try {
sktclose();
} catch (IOException err) {
chattaappend(errtoString());
}
} catch (IOException e) {
chattaappend(etoString());
}
}
public void dataout(String data) {
theOutputStreamprintln(data);
}
}
//软件界面进行按键监听调用
//facejava
import javaawt*;
import javaawtevent*;
public class Face extends Frame {
/**
*
*/
private static final long serialVersionUID = L;
Button clientBtn serverBtn;
TextArea ta;
TextField tfaddress tfport tftype;
int port;
Client client;
Server server;
boolean iamserver;
static Face frm;
public Face() {
clientBtn = new Button(客户端);
serverBtn = new Button(服务器);
ta = new TextArea( TextAreaSCROLLBARS_BOTH);
tfaddress = new TextField( );
tfport = new TextField();
tftype = new TextField();
tftypeaddKeyListener(new TFListener());
tasetEditable(false);
setLayout(new FlowLayout());
add(tfaddress);
add(tfport);
add(clientBtn);
add(serverBtn);
add(ta);
add(tftype);
setSize( );
setTitle(我的聊天室);
thissetVisible(true);
clientBtnaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
port = IntegerparseInt(tfportgetText());
client = new Client(tfaddressgetText() port frm);
clientstart();
tfaddresssetEnabled(false);
tfportsetEnabled(false);
serverBtnsetEnabled(false);
clientBtnsetEnabled(false);
}
});
serverBtnaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
port = IntegerparseInt(tfportgetText());
server = new Server(port frm);
serverstart();
iamserver = true;
tfaddresssetText(成为服务器);
tfaddresssetEnabled(false);
tfportsetEnabled(false);
serverBtnsetEnabled(false);
clientBtnsetEnabled(false);
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit();
}
});
}
public static void main(String args[]) {
frm = new Face();
}
private class TFListener implements KeyListener {
public void keyPressed(KeyEvent e) {
if (egetKeyCode() == KeyEventVK_ENTER) {
taappend(> + tftypegetText() + \n);
if (iamserver)
serverdataout(tftypegetText());
else
clientdataout(tftypegetText());
tftypesetText();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
}
这个程序我限制了连接数大家可以根据自己的需要进行修改