導航:首頁 > 編程語言 > javasocket創建

javasocket創建

發布時間:2023-01-07 14:36:00

java中如何創建socket連接的過程

這是我寫過的一個簡單聊天軟體客戶端 你參考下

importjava.util.*;
importjava.io.*;
importjava.net.*;
importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;

{
privateJTextAreajta=newJTextArea();
privateJTextFieldjtf=newJTextField();
privateJComboBox<String>jcb=newJComboBox<String>();
privateJButtonjbsend=newJButton("send");
privateJButtonjbrefresh=newJButton("refresh");
privateInputStreaminput;
privateOutputStreamoutput;
private Socketsocket;
publicstaticStringSERVER_IP="192.168.1.101";
publicstaticintSERVER_PORT=8888;
//Message1->refreshmessage
//Message2->sendmessage
publictestChatClient()
{
initComponents();
try
{
socket=newSocket(SERVER_IP,SERVER_PORT);
input=socket.getInputStream();
output=socket.getOutputStream();
}
catch(IOExceptione)
{
System.err.println(e);
}
jbrefresh.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
jta.setText("");
try
{
if(socket==null)
socket=newSocket(SERVER_IP,SERVER_PORT);
output.write(0x31);
}
catch(IOExceptionex)
{
JOptionPane.showConfirmDialog(null,ex);
}
}
});
jbsend.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
if(jtf.getText()==null||jtf.getText().equals(""))
return;
if(jtf.getText().length()>=400)
{
JOptionPane.showConfirmDialog(null,"最大字數不能超過400");
return;
}
try
{
Stringdestination=jcb.getSelectedItem().toString();
Stringmessage=jtf.getText();
if(socket==null)
socket=newSocket(SERVER_IP,SERVER_PORT);
byte[]temp=newbyte[3+destination.getBytes().length+message.getBytes().length];
temp[0]=0x32;
temp[1]=(byte)destination.getBytes().length;
inti=2;
for(intj=0;j<destination.getBytes().length;i++,j++)
temp[i]=destination.getBytes()[j];
temp[i++]=(byte)message.getBytes().length;
for(intj=0;j<message.getBytes().length;i++,j++)
{
temp[i]=message.getBytes()[j];
System.out.println();
}
output.write(temp);
jta.append("me: ");
jta.append(jtf.getText());
jta.append(" ");
jtf.setText("");
}
catch(IOExceptionex)
{
System.err.println(ex);
}
}
});
try
{
jbrefresh.doClick();
while(true)
{
byte[]tempBytes=newbyte[1000];
input.read(tempBytes);
intcommand=tempBytes[0]-0x30;
//intreadLength=input.read();
switch(command)
{
case1:
{
intreadLength=tempBytes[1];
String[]temp=newString(tempBytes,2,readLength,"UTF-8").split(";");
jcb.removeAllItems();
if(temp.length==0&&temp[0].equals(""))
return;
for(inti=0;i<temp.length;i++)
{
jcb.addItem(temp[i]);
}
jcb.setSelectedIndex(0);
break;
}
case2:
{
intreadLength1=tempBytes[1];
jta.append(newString(tempBytes,2,readLength1,"UTF-8")+" ");
intreadLength2=tempBytes[2+readLength1];
jta.append(newString(tempBytes,3+readLength1,readLength2,"UTF-8")+" ");
break;
}
}
}
}
catch(IOExceptione)
{
System.err.println(e);
}
}
publicstaticvoidmain(String[]args){
testChatClientframe=newtestChatClient();
}
publicvoidinitComponents()
{
setLayout(newBorderLayout());
JPaneljpNorth=newJPanel();
jpNorth.setLayout(newBorderLayout());
jpNorth.add(jcb,BorderLayout.CENTER);
jpNorth.add(jbrefresh,BorderLayout.EAST);
JPaneljpSouth=newJPanel();
jpSouth.setLayout(newBorderLayout());
jpSouth.add(jtf,BorderLayout.CENTER);
jpSouth.add(jbsend,BorderLayout.EAST);
add(jpNorth,BorderLayout.NORTH);
add(jpSouth,BorderLayout.SOUTH);
add(newJScrollPane(jta),BorderLayout.CENTER);
this.getRootPane().setDefaultButton(jbsend);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,600);
setVisible(true);
}
}

⑵ 編寫代碼,使用java ServerSocket創建伺服器端ServerSocket的過程。

packagesocket;

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.PrintWriter;
importjava.net.ServerSocket;
importjava.net.Socket;

publicclassSocketService{
//搭建伺服器
publicstaticvoidmain(String[]args)throwsIOException{
SocketServicesocketService=newSocketService();
//1、a)創建一個伺服器端Socket,即SocketService
socketService.oneServer();
}
publicvoidoneServer(){
try{
ServerSocketserver=null;
try{
server=newServerSocket(5209);
//b)指定綁定的埠,並監聽此埠。
System.out.println("伺服器啟動成功");
//創建一個ServerSocket在埠5209監聽客戶請求
}catch(Exceptione){
System.out.println("沒有啟動監聽:"+e);
//出錯,列印出錯信息
}
Socketsocket=null;
try{
socket=server.accept();
//2、調用accept()方法開始監聽,等待客戶端的連接
//使用accept()阻塞等待客戶請求,有客戶
//請求到來則產生一個Socket對象,並繼續執行
}catch(Exceptione){
System.out.println("Error."+e);
//出錯,列印出錯信息
}
//3、獲取輸入流,並讀取客戶端信息
Stringline;
BufferedReaderin=newBufferedReader(newInputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
PrintWriterwriter=newPrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
System.out.println("Client:"+in.readLine());
//在標准輸出上列印從客戶端讀入的字元串
line=br.readLine();
//從標准輸入讀入一字元串
//4、獲取輸出流,響應客戶端的請求
while(!line.equals("end")){
//如果該字元串為"bye",則停止循環
writer.println(line);
//向客戶端輸出該字元串
writer.flush();
//刷新輸出流,使Client馬上收到該字元串
System.out.println("Server:"+line);
//在系統標准輸出上列印讀入的字元串
System.out.println("Client:"+in.readLine());
//從Client讀入一字元串,並列印到標准輸出上
line=br.readLine();
//從系統標准輸入讀入一字元串
}//繼續循環

//5、關閉資源
writer.close();//關閉Socket輸出流
in.close();//關閉Socket輸入流
socket.close();//關閉Socket
server.close();//關閉ServerSocket
}catch(Exceptione){//出錯,列印出錯信息
System.out.println("Error."+e);
}
}
}

⑶ java中的socket是什麼意思

所謂socket通常也稱作"套接字",用於描述IP地址和埠,是一個通信鏈的句柄。應用程序通常通過"套接字"向網路發出請求或者應答網路請求。x0dx0a以J2SDK-1.3為例,Socket和ServerSocket類庫位於java.net包中。ServerSocket用於伺服器端,Socket是建立網路連接時使用的。在連接成功時,應用程序兩端都會產生一個Socket實例,操作這個實例,完成所需的會話。對於一個網路連接來說,套接字是平等的,並沒有差別,不因為在伺服器端或在客戶端而產生不同級別。不管是Socket還是ServerSocket它們的工作都是通過SocketImpl類及其子類完成的。x0dx0a重要的Socket API:x0dx0ajava.net.Socket繼承於java.lang.Object,有八個構造器,其方法並不多,下面介紹使用最頻繁的三個方法,其它方法大家可以見JDK-1.3文檔。x0dx0a. Accept方法用於產生"阻塞",直到接受到一個連接,並且返回一個客戶端的Socket對象實例。"阻塞"是一個術語,它使程序運行暫時"停留"在這個地方,直到一個會話產生,然後程序繼續;通常"阻塞"是由循環產生的。x0dx0a. getInputStream方法獲得網路連接輸入,同時返回一個InputStream對象實例。x0dx0a. getOutputStream方法連接的另一端將得到輸入,同時返回一個OutputStream對象實例。x0dx0a注意:其中getInputStream和getOutputStream方法均會產生一個IOException,它必須被捕獲,因為它們返回的流對象,通常都會被另一個流對象使用。x0dx0a2ServerSocket類例子編輯x0dx0ax0dx0apackage com.lanber.socket;x0dx0aimport java.io.DataInputStream;x0dx0aimport java.io.DataOutputStream;x0dx0aimport java.io.IOException;x0dx0aimport java.net.ServerSocket;x0dx0aimport java.net.Socket;x0dx0apublic class ServerDemo {x0dx0a/**x0dx0a* 注意:Socket的發送與接收是需要同步進行的,即客戶端發送一條信息,伺服器必需先接收這條信息,x0dx0a* 而後才可以向客戶端發送信息,否則將會有運行時出錯。x0dx0a* @param argsx0dx0a*/x0dx0apublic static void main(String[] args) {x0dx0aServerSocket ss = null;x0dx0atry {x0dx0ass = new ServerSocket(8888);x0dx0a//伺服器接收到客戶端的數據後,創建與此客戶端對話的Socketx0dx0aSocket socket = ss.accept();x0dx0a//用於向客戶端發送數據的輸出流x0dx0aDataOutputStream dos = new DataOutputStream(socket.getOutputStream());x0dx0a//用於接收客戶端發來的數據的輸入流x0dx0aDataInputStream dis = new DataInputStream(socket.getInputStream());x0dx0aSystem.out.println("伺服器接收到客戶端的連接請求:" + dis.readUTF());x0dx0a//伺服器向客戶端發送連接成功確認信息x0dx0ados.writeUTF("接受連接請求,連接成功!");x0dx0a//不需要繼續使用此連接時,關閉連接x0dx0asocket.close();x0dx0ass.close();x0dx0a} catch (IOException e) {x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0a}x0dx0ax0dx0a3客戶端的例子編輯x0dx0apackage com.lanber.socket;x0dx0aimportjava.io.DataInputStream;x0dx0aimport java.io.DataOutputStream;x0dx0aimportjava.io.IOException;x0dx0aimport java.io.OutputStream;x0dx0aimport java.net.Socket;x0dx0aimport java.net.UnknownHostException;x0dx0apublic class ClientDemo {x0dx0a/**x0dx0a* @param argsx0dx0a*/x0dx0apublic static void main(String[] args) {x0dx0aSocket socket = null;x0dx0atry {x0dx0asocket = new Socket("localhost",8888);x0dx0a//獲取輸出流,用於客戶端向伺服器端發送數據x0dx0aDataOutputStream dos = new DataOutputStream(socket.getOutputStream());x0dx0a//獲取輸入流,用於接收伺服器端發送來的數據x0dx0aDataInputStream dis = new DataInputStream(socket.getInputStream());x0dx0a//客戶端向伺服器端發送數據x0dx0ados.writeUTF("我是客戶端,請求連接!");x0dx0a//列印出從伺服器端接收到的數據x0dx0aSystem.out.println(dis.readUTF());x0dx0a//不需要繼續使用此連接時,記得關閉哦x0dx0asocket.close();x0dx0a} catch (UnknownHostException e) {x0dx0ae.printStackTrace();x0dx0a} catch (IOException e) {x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0a}

⑷ 編寫代碼,使用Java Socket創建客戶端Socket的過程。

如果你要實現伺服器和客戶端都可以向對方發送消息,而不等待對方應答,只需要把InputStream和OutputStream分別放在兩個不同線程里就行了,即是說把接收流與發送流分別用一個線程監聽處理。如果要實現不分客戶端伺服器的話,用UDP通信即可 補充回答:如果不涉及到MIME,只是收發簡單文本郵件。就會比較簡單。因為就像你說的,smtp和pop3協議就是文本格式的。你用Socket建立連接後,就像讀文件一樣,一行一行的讀數據,然後按照協議分析數據格式。例如如果開始時USER那麼後面可能跟的就是用戶等。 就是一個字元串解析和匹配的過程。網上好像有這類代碼,自己找一個學習一下。我以前用C在68k上作過,不是很難。不過代碼已經沒有了。

⑸ java中如何創建socket連接的過程

1、在打開的ie瀏覽器窗口右上方點擊齒輪圖標,選擇「Internet選項」,如下圖所示:

⑹ Java中建立一個socket客戶端需要幾步

代碼給你自己看去:

Socket socket = new Socket("192.168.1.72", 4700);
// 向本機的4700埠發出客戶請求
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));
// 由系統標准輸入構造BuffereadReader對象
PrintWriter os = new PrintWriter(socket.getOutputStream());
// 由socket對象得到輸出流,並創建PrintWriter對象
BufferedReader is = new BufferedReader(new InputStreamReader(
socket.getInputStream(),"UTF-8"));
// 由socket對象得到輸出流,並構建BufferedReader對象
String readLine;
readLine ="客戶端啟動成功!";
System.out.println(readLine);
// 系統由標准輸入讀入一個字元串
while (!readLine.equals("bye")) {
// 若從標准輸入得到的字元串是bye則停止循環
os.println(readLine);
// 將從標准輸入流中得到的字元串輸入到Server
os.flush();
// 刷新輸入流使Server馬上得到該字元串
System.out.println("client:" + readLine);
// 在系統標准輸出上列印輸入該字元串
System.out.println("Server:" + is.readLine());
// 從Server上讀入一字元串並列印
readLine = sin.readLine();
// 從系統標准輸入得到字元串
}
os.close();// 關閉輸入流
is.close();// 關閉輸出流
socket.close();// 關閉socket流
} catch (Exception e) {
e.printStackTrace();
}
}

⑺ java socket怎麼建立連接池

socket連接池

SocketServerPool 含有兩個參數 listenPort , maxConnection 。分別表示監聽埠和最大連接數。

函數setHandlers() 裡面初始化了5個PoolConnectionHandler的線程,表示池中能同時最大處理5個連接。

/**
* @author jake1036
* 2010.7.16 20:05
* socket連接池類
*/
package cn.bupt.net;
import java.io.*;
import java.net.*;

/**
* @author jake1036
*
*/
public class SocketServerPool {

/*最大連接和監聽埠*/
private int maxConnections ;
private int listenPort ;

public SocketServerPool(int listenPort , int maxConnections){
this.listenPort = listenPort ;
this.maxConnections = maxConnections ;

}
public void acceptConnections(){
try {
ServerSocket serverSocket = new ServerSocket(listenPort , 5) ;
Socket socket= null ;
while(true)
{
socket = serverSocket.accept() ;
PoolConnectionHandler.processRequest(socket) ;
}
} catch (IOException e) {
e.printStackTrace();
}

}

public void setHandlers()
{
for(int i = 0 ; i < this.maxConnections ; i++ )
{
PoolConnectionHandler poolHandler = new PoolConnectionHandler() ;
new Thread(poolHandler , "handler" + i).start() ;
}
}

public static void main(String [] args)
{
SocketServerPool pool = new SocketServerPool(8888 , 5) ;
pool.setHandlers() ;
pool.acceptConnections() ;
}

}

⑻ 關於JAVA socket編程

先運行伺服器端類,然後再運行客戶端類,就可以了

/**
*伺服器端類
*/
public class Server {
public static void main(String[] args) throws IOException{
Server server = new Server();
server.start();
}
public void start() throws IOException{
//ServerSocket 對當前伺服器的服務埠的綁定
//這個埠號不能重復綁定,不能同時執行兩邊
ServerSocket ss = new ServerSocket(8888);
while(true){

//accept 開始等待(IO Block)客戶連接(啟動監聽),如果沒有客戶端連接,一直掛起等待下去。
//如果有客戶端連接,才會繼續執行下去,返回的Socket實例s 代表對於客戶端連接。
Socket s = ss.accept();
//創建並啟動客戶服務線程,為客戶服務
//當前線程再次返回到accept等待,下一個客戶連接
new Service(s).start();//創建線程
}
}
class Service extends Thread{
Socket s;
public Service(Socket s){
this.s = s;
}
public void run(){
try{
//s代表客戶端
//s 中的in代表從客戶傳遞過來的流
//s 中的out代表從伺服器到客戶端傳輸流
InputStream in = s.getInputStream();
Scanner sc = new Scanner(in);//System.in是操作系統後台
OutputStream out = s.getOutputStream();
//out.write("您好!您需要點啥?\n".getBytes("GBK"));
//out.flush();//清理緩沖,確保發送到客戶端

while(true){
String str = sc.nextLine();//IO Block
if(str.equals("連接伺服器")){
out.write("連接成功!\n".getBytes("GBK"));
out.flush();
break;
}
}
}catch(IOException e){
e.printStackTrace();
}

}
}
}

/**
*客戶端類
*/
public class Client {
public static void main(String[] args) throws IOException{
// new Socket() 連接到指定的伺服器埠,當前用的是本機的埠
Socket s = new Socket("localhost", 8888);
//返回s代表連接到了伺服器
//s代表對伺服器的連接

InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();

out.write("連接伺服器\n".getBytes("gbk"));
out.flush(); //清理緩沖,確保發送到服務端
Scanner sc = new Scanner(in);
String str = sc.nextLine();
System.out.println(str); //把從伺服器返回的信息,列印到控制台。
out.flush();
}
}

閱讀全文

與javasocket創建相關的資料

熱點內容
循環宏1命令 瀏覽:35
斐波那契數列矩陣演算法 瀏覽:674
公式保護後加密不了 瀏覽:82
java跳轉到jsp 瀏覽:819
327平方根演算法 瀏覽:216
win7美化命令行終端 瀏覽:797
免加密狗圖片 瀏覽:485
一隻透明的鳥是什麼app 瀏覽:817
空氣壓縮機油批發商 瀏覽:69
linuxifexist 瀏覽:4
加密tf卡拷入文件 瀏覽:399
山西php工資 瀏覽:673
福州看病預約用什麼小程序app 瀏覽:238
php保留兩位小數不四捨五入 瀏覽:292
黑馬程序員路徑大全 瀏覽:1000
saas平台PHP 瀏覽:333
雲伺服器科學計算配置怎麼選 瀏覽:649
jar解壓命令 瀏覽:609
php正則問號 瀏覽:299
無線已加密不可上網是怎麼了 瀏覽:466